给定以下代码:
#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/