我到处读到必须在那时和那里初始化引用并且不能再次重新初始化。
为了测试我的理解,我编写了以下小程序。似乎我实际上已经成功地重新分配了参考。有人可以向我解释我的程序中实际发生了什么吗?
#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
原文由 Invictus 发布,翻译遵循 CC BY-SA 4.0 许可协议
No,
ri
is still a reference toi
- you can prove this by printing&ri
and&i
and seeing they’re the same地址。您所做的是修改
i
通过 参考ri
。打印i
之后,你会看到这个。另外,为了比较,如果你创建一个
const int &cri = i;
它不会让你分配给它。