我们可以重新分配 C 中的引用吗?

新手上路,请多包涵

我到处读到必须在那时和那里初始化引用并且不能再次重新初始化。

为了测试我的理解,我编写了以下小程序。似乎我实际上已经成功地重新分配了参考。有人可以向我解释我的程序中实际发生了什么吗?

 #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 许可协议

阅读 619
2 个回答

ri = j; // >>> Is this not reassigning the reference? <<<

No, ri is still a reference to i - you can prove this by printing &ri and &i and seeing they’re the same地址。

您所做的是修改 i 通过 参考 ri 。打印 i 之后,你会看到这个。

另外,为了比较,如果你创建一个 const int &cri = i; 它不会让你分配给它。

原文由 Useless 发布,翻译遵循 CC BY-SA 3.0 许可协议

您不能“重新安装”参考( https://isocpp.org/wiki/faq/references#reseating-refs )。

C++ 中引用的一个有用的口头禅是引用 它们所引用的对象。您对其所做的任何更改 都是 为了更改他们所指的内容。使用咒语,您可能会看到当您执行 ri = j 时发生了什么,我现在 j。

原文由 Sid 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题