无法将类型为"类名 &"的非常量左值引用绑定到类型为"类名"的右值

cannot bind non-const lvalue reference of type 'ClassName &’ to an rvalue of type ‘ClassName’

本文关键字:类名 类型 引用 绑定 常量 非常      更新时间:2023-10-16

这是我的函数原型:

Rational & operator+=(const Rational &);

这是我课程的一部分:

class Rational
{
public:
Rational(int a = 0, int b = 1) : n(a), d(b) {}

这是我的函数:

Rational & Rational::operator+=(const Rational & r)
{
return (r + *this);
}

我已经做了一个函数来添加两个有理数。 当我尝试编译它时,出现以下错误:

error: cannot bind non-const lvalue reference of type 
‘Rational&’ to an rvalue of type ‘Rational’
return (r + *this);

我做错了什么?

你的 operator+ 返回一个新的实例,不是吗?那么,您的退货声明中会发生什么?

  1. 您尝试返回临时结果(这就是错误消息的内容)。

  2. 同时,您没有修改此对象,因此违反了 += 语义(不,通过替换表达式的结果,此值应该是,您没有向编译器提供实际意图的丝毫提示。

你知道,更自然的实现是将真正的数学放在 operator+= 中,然后在 operator+ 中重用它,类似于R retVal = a; return a += b;