为什么可以const int&绑定到一个整数? [英] Why can const int& bind to an int?

查看:40
本文介绍了为什么可以const int&绑定到一个整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++入门中,我发现 const int& 可以与int对象绑定。我不理解,因为我认为 const int& 应该绑定 const int 而不是 int 对象, int 对象可以更改,这本书为 const int& 对象与<$ c绑定时解释了这个问题。 $ c> int ;两者之间有一个临时对象,例如:

In the C++ primer, I found that const int & can bind with a int object.I don't understand that,because I think const int & should bind with a const int not a int object, the int object can change, the book explain this question for that when the const int & object bind with int; there is a temporary object between the two, for example:

int a=0;
const int &r=a;

我们可以使用 b 作为临时值,因此上面的值等于:

We can use b as the temporary value, so above is equal that:

const int b=a;
const int &r=b;

但是我认为这本书是不对的,因为如果有像 b 存在于 a r 之间,其值 r 不能更改,但是当我在Visual Studio中调试以下代码时,我发现它是不正确的:

But I think the book is not right, because if there is a temporary like b existing between a and r,the value of r can't be changed, but when I debug the following coding in visual studio, I found it is not right:

int a=0;
const int &r=a;
a=3;
cout<<r<<endl;

输出为 r = 3; r 的值可以更改,为什么?我不明白。

The output is that r=3; the value of r can be changed, why? I don't understand that.

推荐答案


不明白,因为我认为 const int& 应该绑定 const int 而不是 int object

don't understand that,because I think const int & should bind with a const int not a int object

您误会了。对const的引用(简称const引用)并不意味着只能绑定const对象。

You are mistaken. A reference-to-const (const reference in short) doesn't mean that only const objects can be bound. It means that the object can not be modified through the reference.

不允许的是将非const引用绑定到const对象,因为这样的引用可以

What is not allowed would be to bind a non-const reference to a const object, because such reference could be used to modify the object which would break the constness.


r 可以更改,为什么?

r 指向的对象是修改-可以,因为对象不是const。 r 仍然引用相同的对象,并且该对象未使用 r 进行修改。

The object that r refers to was modified - which is OK because the object isn't const. r still refers to the same object and the object was not modified using r.

具有const引用并不意味着所引用的对象不能更改。

Having a const reference does not mean that the referred object can not change. It means that the object can not be changed using that reference.

如果您希望拥有一个不能更改的对象,则该对象本身必须为const。 const引用不会使所引用的对象成为const。这本书向您展示了如何创建const对象:

If you wish to have an object that can not change, then that object itself has to be const. A const reference does not make the referred object const. The book has shown you how to create a const object:

const int b=a;




我把参考误认为是弱者,因为他们有一段时间相似

I have regarded reference as poiter mistakely,because they are similiar some time.

实际上,引用与指针非常相似。关于此问题的上下文,它们的行为类似。演示:

Indeed, references are very similar to pointers. Regarding the context of this question, they behave similarly. A demo:

int a=0;
const int *r=&a;
a=3;
cout<<*r<<endl;

这篇关于为什么可以const int&amp;绑定到一个整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆