gpt4 book ai didi

c++ - 我们可以在 C++ 中重新分配引用吗?

转载 作者:IT老高 更新时间:2023-10-28 13:22:18 25 4
gpt4 key购买 nike

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

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

#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

最佳答案

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

不,ri仍然是对 i 的引用- 你可以通过打印 &ri 来证明这一点和 &i并且看到它们是同一个地址。

你所做的是修改 i 通过引用 ri .打印 i之后,你会看到这个。

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

关于c++ - 我们可以在 C++ 中重新分配引用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9293674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com