【发布时间】:2012-02-15 12:47:27
【问题描述】:
我到处读到,引用必须在那时和那里被初始化,并且不能再次重新初始化。
为了测试我的理解,我写了以下小程序。似乎我实际上已经成功地重新分配了参考。有人可以向我解释一下我的程序中实际发生了什么吗?
#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
【问题讨论】:
-
我确信最终 c++ 将添加引用重新分配作为一项功能。现在,使用指针。
-
C++ 在 C++11 中添加了std::reference_wrapper。