一、C++中对于一个常量进行引用,实际的执行过程是先建立一个临时变量,被用常量赋值,然后将引用引用此临时变量,对此引用的改变也即改变了临时变量而非原常量。
1.常规情况:
int a = 1;
int &b = a;
b = 2;
cout << a << "\t" << b << endl;
cout << &a << "\t" << &b << endl;
输出为:
a与b的地址是一样的。
2. 对常量引用
int &a = 1;
此种情况编译错误:error C2440: 'initializing' : cannot convert from 'int' to 'int &'。
const int &a = 1;
如此是可通过编译的。
const int &a = 1;
int &b = a;
此种情况编译错误:error C2440: 'initializing' : cannot convert from 'const int' to 'int &'。好像是说,这里a被解释成const int而非const int &。很奇怪。