为什么int& a =< value>在C ++中是不允许的? [英] Why int& a = <value> is not allowed in C++?

查看:132
本文介绍了为什么int& a =< value>在C ++中是不允许的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读关于C ++中的引用。它表示 int& a = 5 给出编译时错误。

I am reading about references in C++. It says that int& a = 5 gives compile time error.

在C ++中思考 - Bruce Eckel 首先为 int 分配存储,并生成绑定到引用的地址。 必须 const ,因为更改不会产生任何意义

In Thinking in C++ - Bruce Eckel, author says that compiler must first allocate the storage for an int and produce the address to bind to the reference. The storage must be const because changing it would make no sense.

在这一点上困惑。我不能理解它背后的逻辑。为什么不能更改存储中的内容?我知道它根据C ++规则无效,但为什么?

I am confused at this point. I am not able to understand the logic behind it. Why can't be change the content in the storage? I understand that it's invalid as per C++ rules, but why?

推荐答案


"The storage must be const because changing it would make no sense."

如果你想要 a 是对const值的引用,必须将其声明为 const ,因为 a

const int &a = 123;
a = 1000; // `a` is referencing to temporary 123, it is not possible to change it
          // We can not change 123 to 1000
          // Infact, we can change a variable which its value is 123 to 1000
          // Here `a` is not a normal variable, it's a reference to a const
          // Generally, `int &a` can not bind to a temporary object

对于非const绑定:

For non-const bindings:

int x = 1;
int &a = x;

a 是对一个左值的引用。简单来说,它是另一个变量的别名,所以在右手,你应该给一个变量。参数 a 在第一次绑定后不能更改并绑定到另一个变量;

a is a reference to a lvalue. Simple speaking, it's an alias name for another variable, so on the right hand you should give a variable. The reference a can not change and bind to another variable after it's first binding;

在C ++ 11中,您可以通过右值引用引用临时对象/值:

In C++11, you can reference to temporary objects/values by rvalue references:

int &&a = 123;

这篇关于为什么int& a =< value>在C ++中是不允许的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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