当我没有给变量赋新值时,为什么变量的值发生了变化?

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

本文关键字:变量 为什么 发生了 变化 新值时      更新时间:2023-10-16

我正在学习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是对(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;

我们将22 (a的值)赋值给d。因为d是b的别名,所以b现在也是22。因为c指向b,所以*c是b的值,现在是22。