引用变量和指针问题
我有一个指向整数变量的指针。然后我将该指针分配给一个引用变量。现在,当我更改指针以指向其他整数变量时,引用变量的值不会改变。谁能解释为什么?
int rats = 101;
int * pt = &rats;
int & rodents = *pt; // outputs
cout << "rats = " << rats; // 101
cout << ", *pt = " << *pt; // 101
cout << ", rodents = " << rodents << endl; // 101
cout << "rats address = " << &rats; // 0027f940
cout << ", rodents address = " << &rodents << endl; // 0027f940
int bunnies = 50;
pt = &bunnies;
cout << "bunnies = " << bunnies; // 50
cout << ", rats = " << rats; // 101
cout << ", *pt = " << *pt; // 50
cout << ", rodents = " << rodents << endl; // 101
cout << "bunnies address = " << &bunnies; // 0027f91c
cout << ", rodents address = " << &rodents << endl; // 0027f940
我们将 pt 分配给兔子,但啮齿类动物的值仍然是 101。请解释原因。
I have a pointer which is pointing to an integer variable. Then I assign this pointer to a reference variable. Now when I change my pointer to point some other integer variable, the value of the reference variable doesn't change. Can anyone explain why?
int rats = 101;
int * pt = &rats;
int & rodents = *pt; // outputs
cout << "rats = " << rats; // 101
cout << ", *pt = " << *pt; // 101
cout << ", rodents = " << rodents << endl; // 101
cout << "rats address = " << &rats; // 0027f940
cout << ", rodents address = " << &rodents << endl; // 0027f940
int bunnies = 50;
pt = &bunnies;
cout << "bunnies = " << bunnies; // 50
cout << ", rats = " << rats; // 101
cout << ", *pt = " << *pt; // 50
cout << ", rodents = " << rodents << endl; // 101
cout << "bunnies address = " << &bunnies; // 0027f91c
cout << ", rodents address = " << &rodents << endl; // 0027f940
We assigned pt to bunnies, but the value of rodents is still 101. Please explain why.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该行
正在创建对
pt
所指向的内容的引用(即rats
)。它不是对指针 pt 的引用。稍后,当您将
pt
指定为指向bunnies
时,您不会期望rodents
引用发生变化。编辑:为了说明@Als点,请考虑以下代码:
第二个
引用
赋值不会不更改引用本身。相反,它将赋值运算符 (=
) 应用于所引用的事物,即value1
。reference
将始终引用value1
并且无法更改。一开始理解起来有点困难,所以我建议您看一下 Scott Meyer 的优秀书籍 有效的 C++ 和 更高效的 C++。他对这一切的解释比我好得多。
The line
is creating a reference to what
pt
is pointing to (i.e.rats
). It's not a reference to the pointerpt
.Later, when you assign
pt
to point tobunnies
, you would not expect therodents
reference to change.EDIT: To illustrate @Als point, consider the following code:
The second
reference
assignment does not change the reference ltself. Instead, it applies the assignment operator (=
) to the thing referred to, which isvalue1
.reference
will always refer tovalue1
and cannot be changed.It's a little tricky to get your head around at first, so I recommend you take a look at Scott Meyer's excellent books Effective C++ and More Effective C++. He explains all this much better than I can.