[英]Why is the value of a variable changed when I did not assign a new value to it?
I am learning pointer and reference variables in C++, and there is a sample code I saw. 我正在学习C ++中的指针和引用变量,并且有一个示例代码。 I am not sure why the value of *c changed from 33 to 22. Could someone help me understand the process? 我不确定* 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 ?
That's a misunderstanding. 那是个误会。 That statement assigns the value of a
(22) to the variable that d
is a reference to ( b
). 该语句将a
(22)的值分配给变量d
,该变量d
是对( b
)的引用。 It does change what d
is a reference to. 确实会改变d
的引用。 Hence, after that line is executed, the value of b
is 22. 因此,在执行该行之后, b
值为22。
Let's run this piece of code step by step: 让我们逐步运行这段代码:
int a = 22;
int b = 33;
We assigned values to a, b. 我们将值分配给a,b。 Not much to say. 没什么好说的。
int* c = &a;
c holds the address of a. c保存a的地址。 *c is the value of a, which is 22 now. * c是a的值,现在是22。
int& d = b;
d is a reference variable to b. d是b的参考变量 。 From now on, d is treated as an alias of b. 从现在开始,d被视为b的别名 。 The value of d is also the value of b, which is 33. d的值也是b的值,即33。
c = &b;
c now holds the address of b. c现在拥有b的地址。 *c is the value of b, which is 33 now. * c是b的值,现在为33。
d = a;
We assigned 22 (value of a) to d. 我们为d分配了22(a的值)。 Since d is an alias of b, b is now also 22. And because c points to b, *c is the value of b, which is now 22. 由于d是b的别名,因此b现在也为22。由于c指向b,因此* c是b的值,现在为22。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.