我到处都读到过引用必须当时当地初始化,而且不能再重新初始化。
为了测试我的理解力,我编写了以下小程序。似乎我已经成功地重新分配了一个引用。谁能给我解释一下我的程序里到底发生了什么?
#include <iostream>
#include <stdio.h>
#include <conio.h>
using namespace std;
int main()
{
int i = 5, j = 9;
int &ri = i;
cout << " ri is : " << ri <<"\n";
i = 10;
cout << " ri is : " << ri << "\n";
ri = j; // >>> Is this not reassigning the reference? <<<
cout << " ri is : " << ri <<"\n";
getch();
return 0;
}
代码编译得很好,输出正如我所期望的那样:
ri is : 5
ri is : 10
ri is : 9