c++ - 为什么我收到此错误 "invalid initialization of non-const reference of type ' A &' from an rvalue of type ' A'"

标签 c++ c++11 reference

给定以下代码:

#include <iostream>
using std::ostream;

class A {
    int x;
public:
    A(int x) :
            x(x) {
    }
    A& operator+=(const A& a) {
        this->x = this->x + a.x;
        return *this;
    }
    friend ostream& operator<<(ostream& os, const A& a);

};

A operator+(const A& a1, const A& a2) {
    return A(a1) + a2;
}

ostream& operator<<(ostream& os, const A& a) {
    return os << a.x;
}

int main() {
    const A a1(2);
    A& sum = a1 + a1; // error**************
    std::cout << sum;
}

我收到以下错误:

invalid initialization of non-const reference of type 'A&' from an rvalue of type 'A'

但是我不明白这个错误的原因是什么。 总而言之,我从 operator+ 获取了新对象,并定义了一个对此对象的引用 (sum),那么这种方式有什么问题呢?我该如何解决?

最佳答案

A operator+(const A& a1, const A& a2)

这将返回类型为 A 的新对象(匿名临时对象)。

A& sum = a1 + a1;

您尝试将此临时绑定(bind)到(非常量)引用;因此试图制作对生命周期即将结束的对象的引用。希望这在 C++ 中是不合法的。您确实需要将此对象“存储”在某处:

A sum = a1 + a1;

一个特例:

A const& sum = a1 + a1;

当临时对象绑定(bind)到常量引用时,此对象的生命周期会延长到引用的生命周期。这对于函数参数很有用,但此处不建议。

关于c++ - 为什么我收到此错误 "invalid initialization of non-const reference of type ' A &' from an rvalue of type ' A'",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51065783/

相关文章:

c++ - 用 C++ 编写的 Apache Thrift 服务器抛出 TTransportException

c++ - C/C++ 中的并发日志文件访问

c++ - 如何与特定模板特化成为 friend ?

C++11 随机数分布在不同平台之间不一致——有什么替代方案?

c++ - 具有推导的 void 返回类型的 Constexpr 类模板成员函数?

wpf - 如何在 Grid.Row/Grid.Column 中引用行/列定义?

c++ - 尝试创建 Qt 4.7 QStrings,填充到指针数组中

silverlight - 缺少 System.Windows 引用

C#/.NET 项目 - 我的设置是否正确?

c++ - 光学字符识别 : Difference between two frames