C++中关于&的一些。int i 与 int &i 注意事项
2015-01-29 14:26
337 查看
1.int i 传值,int & i 传引用
int i不会回带参数,而int &i可以回带参数,如[cpp]
view plaincopy
#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 不能
[cpp]view plaincopy
#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 只是拷贝
[cpp]view plaincopy
#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;
}
最后,我们再来看一下个例子
[cpp]
view plaincopy
#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的构造函数的参数传递为传值方式,所以,当调用时,相当于有一个
[cpp]
view plaincopy
int b = 60
存在,而 i2(b) 相当于将
[cpp]
view plaincopy
int &i2 = b;
而当构造函数调用完成,b的作用域结束,b被销毁,而i2指向一个已经被销毁的地方,所以会出现未定义的运行结果。
我们再贴一段程序,和上面的一段相对应,只是,这次,我们将会获得 45 60 的结果
[cpp]
view plaincopy
#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;
}
相关文章推荐
- C++中 int i 与 int &i 注意事项
- C++中 int i 与 int &i 注意事项
- 关于c++的一些注意事项
- 关于在c#里加载c++ dll的一些注意事项
- C++ 关于MFC多线程编程中的一些注意事项 及自定义消息的处理
- 关于c++的一些注意事项
- C++中关于cons和字符串t的一些注意事项
- 关于linux动态链接库的一些注意事项
- 关于discovery的一些澄清和注意事项
- Asp.net &C#开发中的一些注意事项及小技巧
- 关于 (int&)a 的一些讨论
- 关于U盾使用的一些注意事项
- 关于PerSession下一些方法调用的注意事项
- 关于C/C++中 常量应用的注意事项
- iBaits中,关于insert返回值的问题(注意!!!不必写resultClass= "java.lang.Integer",方法的返回值就是int)
- 个人关于PHP5中oop的一些注意事项
- OSGI 中关于Module层包共享的一些注意事项
- [c++ primer plus]c++ compiler缺省生成了哪些构造函数?关于构造函数的注意事项。
- c++中 关于字符串的一些需要注意的问题
- 关于指针的一些注意事项