当我没有给变量赋新值时,为什么变量的值发生了变化?
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
是对(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。
相关文章:
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 为什么我的变量没有更新,我的 LED 没有亮起?
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 为什么C++有不同的变量初始化方式?
- 如果全局变量默认是外部变量,为什么要添加"extern"关键字?
- 为什么未命名的结构内联变量在每个翻译单元中没有相同的地址?
- 为什么我可以将变量存储在不是其最小对齐方式的倍数的地址?
- 为什么thread_local变量在这里从未初始化?
- 为什么内存屏障依赖于变量?
- 为什么我的变量存在于其范围之外
- 为什么我们再次从结构对象创建结构变量?
- 字符串与字符* 作为类成员变量.为什么要使用字符*
- 如何读取文件内容并将其保存到字符串类型变量?为什么有空白空间
- 将char * *变量赋值给char * const *变量——为什么允许这样做?
- 在类中传递私有变量——为什么不允许这样做
- 引用临时变量 - 为什么编译器没有检测到它?
- 访问类中的私有成员变量:为什么这样做
- 全局变量-C++为什么这种方式很危险
- ' ios_base '的标志都是静态const整型变量.为什么可以用' ios_base::setf() '来