为什么运算符'='无法匹配?

时间:2013-09-02 03:12:50

标签: c++

我经常遇到编译错误:

  

'bObj1 =中的'operator ='不匹配   Balance :: operator +(Balance&)(((Balance&)(& bObj2)))'

你能帮助指出原因吗? 提前谢谢。

代码:

class Balance
{
public:
    Balance (int b = 0) {balance = b;};
    Balance (Balance &);

    Balance & operator= (Balance &);
    Balance operator+ (Balance &);

    int get() {return balance;};
    void set(int b) {balance = b;};

private:
    int balance;
};

Balance & Balance::operator=(Balance &copy)
{
    balance = copy.get();
    return *this;
}

Balance Balance::operator+ (Balance &rig)
{
    Balance add;
    add.set(this->get() + rig.get());
    return add;
}

int main()
{
    Balance bObj1, bObj2(100);
    bObj1 = bObj2;
    bObj1 = bObj1 + bObj2; // This line cause the error.
    return 0;
}

2 个答案:

答案 0 :(得分:2)

您的作业运算符错误。你可以安全地删除它,因为隐式运算符足以让你简单的类。 请阅读When do I need to write an assignment operator?了解详情。

class Balance
{
public:
  Balance (int b = 0) {balance = b;};
  Balance operator+ (const Balance &);

  int get() const {return balance;};
  void set(int b) {balance = b;};

private:
  int balance;
};

Balance Balance::operator+ (const Balance &rig)
{
  Balance add;
  add.set(this->get() + rig.get());
  return add;
}

答案 1 :(得分:0)

使用非const引用的运算符覆盖时会出现问题。将您的函数更改为const:

Balance & operator= (const Balance &);
Balance operator+ (const Balance &) const;

int get() const { return balance; }

当应用+运算符时,结果是 rvalue ,它是不可变的。由于您的=无法接受rvalue引用(因为它不是const),因此编译器无法匹配运算符。

上面,我已经使你的功能对rvalue友好。 =运算符将接受右值。 +运算符也接受rvalue并且为const,因为它不会修改对象。因为它是const,所以我也使用了get函数const。

相关问题