我们说Reference是const指针。为什么我能够为 ref B 分配一个新变量?下面的程序编译成功
#include<iostream.h>
int main()
{
int a=10;
int &b=a;
cout<<"B"<<'\n'<<b;
cout<<"A"<<'\n'<<a;
b=100;
cout<<"B"<<'\n'<<b;
cout<<"A"<<'\n'<<a;
int c=20;
b=c;
cout<<"C"<<'\n'<<c;
cout<<"B"<<'\n'<<b;
}
#include<iostream.h>
int main()
{
int a=10;
int &b=a;
cout<<"B"<<'\n'<<b;
cout<<"A"<<'\n'<<a;
b=100;
cout<<"B"<<'\n'<<b;
cout<<"A"<<'\n'<<a;
int c=20;
b=c;
cout<<"C"<<'\n'<<c;
cout<<"B"<<'\n'<<b;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
引用不是 const 指针。需要取消引用 const 指针才能访问该值。您不需要取消引用引用。
引用是别名——同一事物的新名称。所以你问题中的代码是有效的,并且 a 和 b 指的是同一件事。
A reference is not a const pointer. A const pointer would need to be dereferenced to access the value. You don't need to dereference references.
A reference is an alias - a new name for the same thing. So the code in your question is valid and a and b refer to the same thing.
我希望您不会对以下内容感到困惑:
b=c;
这只会将 c 的值分配给 b。它不会引用c。 (它仍然会引用 a 本身)
I hope you are not getting confused with :
b=c;
This will only assign the value of c to b. It will not refer to c. ( It will still refer to a itself)
您并不是为
b
分配一个新变量(引用者),而是为b
引用的变量分配一个新值,在本例中为a
。Your are not assigning a new variable (referee) to
b
, but a new value to the variableb
refers to, in this casea
.引用类似于 const 指针,但与指向 const 对象的指针不同。
引用与后者类似 - 一旦初始化,它们就不能引用另一个对象。
A reference is similar to a const pointer but not to a pointer to const object.
References are similar to the latter - once initialized, they can't be made to refer to another object.
引用根本不是指针。
Reference is not pointer at all.
当你执行 b = c 时,你并不是指 c,而是只是将 c 的值赋给 b。如果您想验证 c 的增量值并打印 b 和 c。
when you are doing b = c, you are not referring to c instead you are just assigning value of c to b. If you want verify increment value of c and print both b and c.