繁体   English   中英

当我没有给变量赋值时,为什么变量的值会改变?

[英]Why is the value of a variable changed when I did not assign a new value to it?

我正在学习C ++中的指针和引用变量,并且有一个示例代码。 我不确定* c的值为什么从33变为22。有人可以帮助我理解此过程吗?

int a = 22;
int b = 33;
int* c = &a; //c is an int pointer pointing to the address of the variable 'a'
int& d = b; //d is a reference variable referring to the value of b, which is 33.
c = &b; //c, which is an int pointer and stored the address of 'a' now is assigned address of 'b'
std::cout << "*c=" << *c << ", d=" << d << std::endl; //*c= 33 d= 33
d = a; //d is a reference variable, so it cannot be reassigned ?
std::cout << "*c=" << *c << ", d=" << d << std::endl; //*c= 33 d= 33
 d = a; //d is a reference variable, so it cannot be reassigned ? 

那是个误会。 该语句将a (22)的值分配给变量d ,该变量d是对( b )的引用。 确实会改变d的引用。 因此,在执行该行之后, b值为22。

让我们逐步运行这段代码:

int a = 22;
int b = 33;

我们将值分配给a,b。 没什么好说的。

int* c = &a;

c保存a的地址。 * c是a的值,现在是22。

int& d = b;

d是b的参考变量 从现在开始,d被视为b的别名 d的值也是b的值,即33。

c = &b;

c现在拥有b的地址。 * c是b的值,现在为33。

d = a;

我们为d分配了22(a的值)。 由于d是b的别名,因此b现在也为22。由于c指向b,因此* c是b的值,现在为22。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM