gpt4 book ai didi

当文档另有建议时,c++ 引用似乎已重新分配

转载 作者:太空狗 更新时间:2023-10-29 23:25:34 26 4
gpt4 key购买 nike

根据 this问题你不能改变引用指的是什么。同样,C++ Primer 第 5 版指出

Once we have defined a reference, there is no way to make that reference refer to a different object. When we use a reference, we always get the object to which the reference was initially bound.

然而下面的代码compiles并打印值 4,在我看来,引用值已更改??请详细说明是否如此。

int a = 2;
int b = 4;
int &ref = a;
ref = b;
cout << ref;

最佳答案

您没有重新分配引用。引用充当变量的别名。在这种情况下,refa 的别名,所以

ref = b;

相当于

a = b;

您可以通过打印出 a 的值轻松检查:

std::cout << a << std::endl; // prints 4

关于当文档另有建议时,c++ 引用似乎已重新分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16862058/

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