【问题标题】:cannot bind non-const lvalue reference of type 'ClassName &’ to an rvalue of type ‘ClassName’ [closed]无法将“ClassName &”类型的非常量左值引用绑定到“ClassName”类型的右值 [关闭]
【发布时间】:2018-03-11 19:21:03
【问题描述】:

这是我的函数原型:

  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);

我做错了什么?

【问题讨论】:

  • 您似乎不知道简单的技巧:首先在谷歌上搜索错误消息通常是个好主意...

标签: c++ class oop pointers


【解决方案1】:

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

  1. 您尝试返回一个临时结果(这就是错误消息的含义)。

  2. 1234563 .)

您知道,更自然的实现是将真正的数学运算放在 operator+= 中,然后在 operator+ 中重用它,例如 R retVal = a; return a += b;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-07
    • 1970-01-01
    • 2021-03-03
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多