gpt4 book ai didi

c++ - "A reference may be bound only to an object",为什么 "const int &ref = 3;"有效?

转载 作者:行者123 更新时间:2023-11-30 01:55:44 26 4
gpt4 key购买 nike

我刚刚开始学习 C++。我在网上找到了一个建议:“看一本好书,比看youtube上的视频更好。”因此,当我有动力并且有时间学习 c++ Primer 5th Ed 时。

在这本书中,他们说:注意:“引用不是对象。相反,引用只是已存在对象的另一个名称。”

和:“引用只能绑定(bind)到一个对象,而不是文字或更一般表达式的结果”

我明白了:

int i = 3;
int &ri = i; // is valid: ri is a new name for i
int &ri2 = 2; // is not valid: 2 is not an object

那我不明白为什么:

const int &ri3 = 2;  // is valid

他们写道:“理解复杂的指针或引用声明会更容易,如果你从右到左阅读它们。”

好吧,这不是很复杂。我明白:我声明了一个名为 ri3 的变量,它是一个引用(当 & 在类型之后时是引用,当 & 在表达式中时是地址)到一个 int 类型的对象并且它是一个常数。

我认为它已经解释了很多次,但是当我在论坛上搜索时,我发现复杂问题的复杂(对我来说)答案,我仍然不明白。

感谢您的帮助。

最佳答案

https://stackoverflow.com/a/7701261/1508519

You cannot bind a literal to a reference to non-const (because modifying the value of a literal is not an operation that makes sense). You can however bind a literal to a reference to const.

http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/

The "const" is important. The first line is an error and the code won’t compile portably with this reference to non-const, because f() returns a temporary object (i.e., rvalue) and only lvalues can be bound to references to non-const.

为了便于说明,请参阅此 answer .

A non-const reference cannot point to a literal.

以下代码会产生错误。

error: invalid initialization of non-const reference of type 'double&' from an rvalue of type 'double'

#include <iostream>

double foo(double & x) {
x = 1;
}

int main () {
foo(5.0);
return 0;
}

这是 Lightness ' 评论。

[C++11: 5.1.1/1]: [..] A string literal is an lvalue; all other literals are prvalues.

cppreference (向下滚动到 rvalue (until C++11)/prvalue (since C++11)):

A prvalue ("pure" rvalue) is an expression that identifies a temporary object (or a subobject thereof) or is a value not associated with any object.

The following expressions are prvalues:

Literal (except string literal), such as 42 or true or nullptr.

关于c++ - "A reference may be bound only to an object",为什么 "const int &ref = 3;"有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20443262/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com