我在很多地方都读过关于引用文献:
Reference is like a const pointer
Reference always refer to an object
Once initialised, a Reference cannot be reseated
最后一点我想说清楚。这是什么意思?
我试过这段代码:
#include <iostream>
int main()
{
int x = 5;
int y = 8;
int &rx = x;
std::cout<<rx<<"\n";
rx = y; //Changing the reference rx to become alias of y
std::cout<<rx<<"\n";
}
输出
5
8
那么“无法重新设置引用”是什么意思?
最佳答案
这一行:
rx = y;
不使 rx 指向 y。它使 x 的值(通过引用)成为 y 的值。见:
#include <iostream>
int main()
{
int x = 5;
int y = 8;
int &rx = x;
std::cout << rx <<"\n";
// Updating the variable referenced by rx (x) to equal y
rx = y;
std::cout << rx <<"\n";
std::cout << x << "\n";
std::cout << y << "\n";
}
因此不可能在初始分配后更改 rx 所引用的内容,但您可以更改被引用的内容的值。
因此,就此示例而言,引用类似于常量指针(其中指针地址是常量,而不是该地址处的值)。然而,存在重要差异,一个很好的例子(正如 Damon 所指出的)是您可以将临时对象分配给本地 const 引用,并且编译器将延长它们的生命周期以在引用的生命周期内持续存在。
关于引用和 const 指针之间差异的更多详细信息可以在 this SO post 的答案中找到。 .
关于c++ - 引用 - const 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11409679/