2.引用更接近const指针,必须在创建时进行初始化,一旦引用和某个变量关联起来,该引用就会一直指向该变量。
int rats =10;
int&rodents = rats;
上面代码实际上是下述代码的伪装表示:
int rats =10;
int*const pr =&rats;
例子:
#include<iostream>
usingnamespace std;
int main()
{
int rats =100;
int&rodent = rats;
cout <<"rats = "<<rats<<", rosent = "<<rodent<<endl;
cout <<"rats address = "<<&rats<<endl;
cout <<"rosent address = "<<&rodent<<endl;
cout <<"==================================="<<endl;
int bunnies =50;
rodent = bunnies;
cout <<"rats = "<<rats<<", rosent = "<<rodent<<", bunnies = "<<bunnies<<endl;
cout <<"rats address = "<<&rats<<endl;
cout <<"rosent address = "<<&rodent<<endl;
cout <<"bunniess address = "<<&bunnies<<endl;
return0;
}
输出结果:
rats =100, rosent =100
rats address =0xbfce21e4
rosent address =0xbfce21e4
===================================
rats =50, rosent =50, bunnies =50
rats address =0xbfce21e4
rosent address =0xbfce21e4
bunniess address =0xbfce21e8
从结果可以看出,虽然在调用 rodent = bunnies; 后引用 rosent 的值变为 50,但是 rosent 所指向的地址空间还是指向了 rats,没有发生改变,说明 rodent = bunnies; 只是将 bunnies 的值赋值给引用 rodent 所指向的变量,没有改变引用的指向。