为什么更改引用指向的内容不会引发错误?
我的 C++ 研究已经到了关于参考文献的阶段。它规定了以下规则:
一旦初始化了对某个对象的引用,就不能将其更改为引用另一个对象。
Iv 编写了一个简短的代码(按照练习中的要求),旨在证明该规则是正确的。
int y = 7;
int z = 8;
int&r = y;
r = z;
有人可以解释为什么这段代码编译时没有任何错误或警告吗?
Iv got to the stage in my c++ study concerning references. It states the following rule:
Once a reference is initialized to an object, it cannot be changed to refer to another object.
Iv wrote a short code (as asked to in an exercise) that is meant to prove this rule correct.
int y = 7;
int z = 8;
int&r = y;
r = z;
Can someone explain why this code compiles without any errors or warnings?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
r = z
不会改变r
“指向”的内容。它将z
的值赋给r
指向的对象。以下代码与您的代码执行相同的操作,但使用指针而不是引用:
r = z
does not change whatr
"points to." It assigns the value ofz
to the object pointed to byr
.The following code does the same thing as your code, but using pointers instead of references:
它不会为其他内容创建引用别名,但会更改
r
包含的内容的值。r
是对y
的引用,改变
y
的值&通过将z
的值分配给r
& 将r
的值赋给z
的值因此y
。It does not make the reference alias to something else but it changes the value of what
r
contains.r
is reference toy
changes value of
y
&r
to value ofz
by assigning value ofz
tor
& hencey
.它不会改变参考。相反,它更改引用变量指向的值。引用变量只是 y 的另一个名称。因此,
r=z
相当于 即,
r=z
更改了y
的值。引用变量无法以任何方式重置为引用另一个变量。
It does NOT change the reference. Rather it changes the value pointed to by the reference variable. The reference variable is just yet another name of
y
. Sor=z
is equivalent toThat is,
r=z
changes the value ofy
.Reference variable cannot be reset to refer to another variable, in any way.
您不会更改引用;而是会更改引用。您正在为引用的对象设置一个新值。在此示例之后,您应该注意到 y==8。
You're not changing the reference; you're setting a new value to the referred object. After this example you should note that y==8.
当您执行
r = z
时,您并没有重新定位引用,而是将z
的值复制到y
中>。When you do
r = z
you are not reseating the reference, instead you are copying the value ofz
intoy
.我在学习<时遇到了同样的问题。第11章。
这是我的理解代码:第二个编译错误似乎无法模拟。但可以理解。你可以画图看看x、y、z和ref2指向什么。
I faced the same issue when study <<thinking in c++> charpter11.
here is my understanding code: the second compile error seems can not be simulated. but can understand. you can draw a picture to see what x, y, z, and ref2 point to.