C++中 int i 与 int &i 注意事项
2013-12-02 22:09
525 查看
1.int i 传值,int & i 传引用
int i不会回带参数,而int &i可以回带参数,如#include <iostream> void test1(int i) { i = 7; } void test2(int &i) //要限制参数改动,可以加const限制 { i = 7; } int main() { int t1 = 10; test1(t1); std::cout << t1 << std::endl; //输出为10 int t2 = 10; test2(t2); std::cout << t2 << std::endl; //输出为7 return 0; }
2. int i 可赋予常量,而int & i 不能
#include <iostream> void test1(int i) { i = 7; } void test2(int &i) { i = 7; } int main() { int i = 10; //合法 int &i1 = 10; //编译错误 test1(10); //合法 test2(10); //编译错误 return 0; }
3. int &i 相当于别名,而int i 只是拷贝
#include <iostream> int main() { int t1 = 10; int t2 = 10; int i1 = t1; //复制 int &i2 = t2; //别名 i1 = 7; i2 = 7; std::cout << t1 << std::endl; //输出10 std::cout << t2 << std::endl; //输出7 return 0; }
最后,我们再来看一下个例子
#include <iostream> class A{ public: A(int a, int b):i1(a),i2(b){}; public: int i1; int &i2; }; int main() { A a(45,60); std::cout << a.i1 << " " << a.i2 << std::endl; return 0; }
在电脑上运行之后,你会发现,第一个数字正常,而第二个数字明显是一个未定义的值,例如我运行后得到的结果是
45 1400458944
这是因为我们在构造一个对象的时候,调用了构造函数,而A的构造函数的参数传递为传值方式,所以,当调用时,相当于有一个
int b = 60
存在,而 i2(b) 相当于将
int &i2 = b;而当构造函数调用完成,b的作用域结束,b被销毁,而i2指向一个已经被销毁的地方,所以会出现未定义的运行结果。
我们再贴一段程序,和上面的一段相对应,只是,这次,我们将会获得 45 60 的结果
#include <iostream> class A{ public: A(int a, int &b):i1(a),i2(b){}; public: int i1; int &i2; }; int main() { int t = 60; A a(45,t); std::cout << a.i1 << " " << a.i2 << std::endl; return 0; }
相关文章推荐
- Sample 4.20:ptrstr.cpp
- Sample 4.19:addpntrs.cpp
- Sample 4.18:arraynew.cpp
- Sample 4.17:use_new.cpp
- Sample 4.16:init_ptr.cpp
- Sample 4.15:pointer.cpp
- Sample 4.14:address.cpp
- Sample 4.13:arrstruct.cpp
- C语言动态存储分配
- Sample 4.12:assgn_st.cpp
- Sample 4.11:structur.cpp
- Sample 4.9:strtype3.cpp
- Sample 4.8:strtype2.cpp
- Sample 4.7:strtype1.cpp
- Sample 4.6:numstr.cpp
- Sample 4.5:instr3.cpp
- Sample 4.4:instr2.cpp
- Sample 4.3:instr1.cpp
- Sample 4.2:string.cpp
- Keil C51对C语言的关键词扩展之十七: sbit