1.引用必须在声明时将其初始化,不能先声明后赋值。
#include <iostream> using namespace std; int main() { int rats = 10; //声明引用,旦未初始化 int &rodents; rodents = rats; return 0; }
上述代码编译时会报以下错误:
error: ‘rodents’ declared as reference but not initialized
错误:'rodents' 声明为引用但未初始化。
2.引用更接近const指针,必须在创建时进行初始化,一旦引用和某个变量关联起来,该引用就会一直指向该变量。
int rats = 10; int &rodents = rats;
上面代码实际上是下述代码的伪装表示:
int rats = 10; int * const pr = &rats;
例子:
#include <iostream> using namespace std; int main() { int rats = 100; int &rodent = rats; cout << "rats = "<<rats<<", rodent = "<<rodent<<endl; cout << "rats address = "<<&rats<<endl; cout << "rodent address = "<<&rodent<<endl; cout <<"==================================="<<endl; int bunnies = 50; rodent = bunnies; cout << "rats = "<<rats<<", rodent = "<<rodent<<", bunnies = "<<bunnies<<endl; cout << "rats address = "<<&rats<<endl; cout << "rodent address = "<<&rodent<<endl; cout << "bunniess address = "<<&bunnies<<endl; return 0; }
输出结果:
rats = 100, rodent = 100 rats address = 0xbfce21e4 rodent address = 0xbfce21e4 =================================== rats = 50, rodent = 50, bunnies = 50 rats address = 0xbfce21e4 rodent address = 0xbfce21e4 bunniess address = 0xbfce21e8
从结果可以看出,虽然在调用 rodent = bunnies; 后引用 rosent 的值变为 50,但是 rosent 所指向的地址空间还是指向了 rats,没有发生改变,说明 rodent = bunnies; 只是将 bunnies 的值赋值给引用 rodent 所指向的变量,没有改变引用的指向。
1.引用必须在声明时将其初始化,不能先声明后赋值。
#include <iostream> using namespace std; int main() { int rats = 10; //声明引用,旦未初始化 int &rodents; rodents = rats; return 0; }
上述代码编译时会报以下错误:
error: ‘rodents’ declared as reference but not initialized
错误:'rodents' 声明为引用但未初始化。
2.引用更接近const指针,必须在创建时进行初始化,一旦引用和某个变量关联起来,该引用就会一直指向该变量。
int rats = 10; int &rodents = rats;
上面代码实际上是下述代码的伪装表示:
int rats = 10; int * const pr = &rats;
例子:
#include <iostream> using namespace 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; return 0; }
输出结果:
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 所指向的变量,没有改变引用的指向。