我们说Reference是const指针。为什么我能够为 ref B 分配一个新变量?下面的程序编译成功

发布于 2024-08-26 06:05:18 字数 343 浏览 2 评论 0原文

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

流云如水 2024-09-02 06:05:18

引用不是 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.

为你鎻心 2024-09-02 06:05:18

我希望您不会对以下内容感到困惑:

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)

画骨成沙 2024-09-02 06:05:18

您并不是为 b 分配一个新变量(引用者),而是为 b 引用的变量分配一个新值,在本例中为 a

Your are not assigning a new variable (referee) to b, but a new value to the variable b refers to, in this case a.

橘亓 2024-09-02 06:05:18

引用类似于 const 指针,但与指向 const 对象的指针不同。

const int* p; //can't change the value of *p
int* const p; //can't change p (make it point to a different int)

引用与后者类似 - 一旦初始化,它们就不能引用另一个对象。

A reference is similar to a const pointer but not to a pointer to const object.

const int* p; //can't change the value of *p
int* const p; //can't change p (make it point to a different int)

References are similar to the latter - once initialized, they can't be made to refer to another object.

痴梦一场 2024-09-02 06:05:18

引用根本不是指针。

int const & b1 = a; // const reference
int       & b2 = a  // non-const reference

Reference is not pointer at all.

int const & b1 = a; // const reference
int       & b2 = a  // non-const reference
如梦 2024-09-02 06:05:18

当你执行 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文