#include <iostream>
using namespace std;
int main ()
{
int x = 0;
int y = 1;
int& z = x;
z = x;
z = y;
cout << "\nx: " << x;
cout << "\ny: " << y;
cout << "\nz: " << z;
return 0;
}
**
** 对于所有3个案例,此代码返回1。这不应该是错误吗?
8.5.3 C ++标准部分说:
之后无法更改引用以引用其他对象 初始化。请注意,处理2引用的初始化 与赋值完全不同。论证传递(5.2.2)和 函数值return(6.6.3)是初始化。
答案 0 :(得分:6)
不,在您的代码中,您不会更改z
引用,而是更改z
的内容(以及它引用的内容,x
)。< / p>
您可以使用以下代码查看此内容:
x = 5;
cout << x;
cout << z;
x
和z
的值均为5,因为z
仍然是对x
的引用。
答案 1 :(得分:1)
z = x
z = y
不会更改引用,而是更改x
的值。
答案 2 :(得分:1)
{ int x = 0; // Let x be located at memory 0x1234
int y = 1; // Let y be located at memory 0x5678
int& z = x; //There is a variable call z that is a reference to x.
//That is z refers to the same memory location and thus the same content.
z = x; //Set the contents of z to the content of x.
//Since z is currently a reference to x this essentially does nothing.
z = y; //Set the contents of z to the content of y which is the
//same as set the contents of memory 0x1234 to the contents of memory 0x5678.
cout << "\nx: " << x; //print the contents of memory 0x1234
cout << "\ny: " << y; //print the contents of memory 0x5678
cout << "\nz: " << z; //print the contents of memory 0x1234
return 0;
}
它没有给你一个错误,因为你没有改变任何内存指针,而是改变它们的内容
答案 3 :(得分:0)
不,这不会产生错误。如上所述,为z赋值与将值赋值给它所引用的值相同,在本例中为x。
在这种情况下,标准规定z必须参考x。 z不能用来引用其他变量。