7

我正在阅读 C++ 中的参考资料。它说这int& a = 5会产生编译时错误。

Thinking in C++ - Bruce Eckel中,作者说编译器必须首先为int分配存储空间并生成绑定到引用的地址。存储必须const,因为更改它没有任何意义

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

4

3 回答 3

6

“存储必须是 const,因为更改它没有任何意义。”

如果要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

对于非常量绑定:

int x = 1;
int &a = x;

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

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

int &&a = 123;
于 2013-10-15T07:40:01.717 回答
5
int& a = 5;

为了使上述代码正常工作,int&需要绑定到int由表达式创建的类型的临时对象5。但是绑定int&到临时文件并没有吸引 Bjarne Stroustrup ——他举了一个类似于下面的例子来说明他的观点:

void f(int &i) { ++i; }

float x = 10.0;
f(x); 
std::cout << x <<< std::endl;

std::cout打印1会是什么?看起来它会打印11

感觉++i正在改变论点,x但事实并非如此。这就是 C++ 的创建者不允许临时对象绑定到非常量引用的原因之一。

但是,您可以这样做:

int const & i = 10;
int const & j = x; //x is float

从 C++11 开始,您可以这样做:

int && i = 10;
int && i = x; //x is float

希望有帮助。


1.假设int&可以绑定到临时创建出来的x

于 2013-10-15T07:50:36.170 回答
0

你能做的是

int b=5;
int &a=b;

或者

const int& a = 5;
于 2013-10-15T07:50:49.067 回答