gpt4 book ai didi

c++ - C++ Primer 中的引用重新分配

转载 作者:行者123 更新时间:2023-11-30 03:18:41 28 4
gpt4 key购买 nike

在 C++ Primer 5th Edition 中,有一个关于引用和 const 的部分,在第 97-98 页:

const int temp = dval;   // create a temporary const int from the double
const int &ri = temp; // bind ri to that temporary

In this case, ri is bound to a temporary object. A temporary object is an unnamed object created by the compiler when it needs a place to store a result from evaluating an expression. C++ programmers often use the word temporary as an abbreviation for temporary object. Now consider what could happen if this initialization were allowed but ri was not const. If ri weren’t const, we could assign to ri. Doing so would change the object to which ri is bound.

我可能是错的,但我认为引用不能被“重新安置”或“重新绑定(bind)”。我的问题是最后一句话:

如果 ri 不是 const,我们可以给 ri 赋值。这样做会改变ri 绑定(bind)到的对象。

这是书上的错误,还是我误解了什么?

根据我的理解,引用可以被认为是变量的别名 或替代名称,尽管我不完全确定这是否正确。

谢谢你的时间

最佳答案

Doing so would change the object to which ri is bound.

这句话有点歧义。您将其解读为“这样做会改变 ri 绑定(bind)到的对象”,但这不是作者的意思。它应该被解读为

Doing so would make changes to an object (namely the one ri is bound to).


From my understanding, a reference can be thought of an alias or alternative name for a variable

完全正确。例如:

int i = 0;
int &r = i;
r = 42;

这里 ri 的别名,所以最后一行对 r 的赋值发生了变化(即设置为 42 ) r 绑定(bind)到的对象(即 i)。换句话说,它将 i 设置为 42

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

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