非成员 += C++重载

non member += overloading in C++

本文关键字:C++ 重载 成员      更新时间:2023-10-16
#include <iostream>
class A
{
public:
  int a;
  A() { a = 2;}
  A(int f) { a= f;}
  void print() { std::cout << a << std::endl; }
};
class B
{
  A a, at, at2;
  A& operator += (A& b)
  {
    a.a = a.a + b.a;
    return a;
  }
public:
  B(int a_, int at_, int at2_) : a(a_), at(at_), at2(at2_) {};
  void update ()
  {
    a += at;
  }
  void printAll() { a.print(); at.print();}
};
int main()
{
  B value ( 2, 3, 5);
  value.printAll();
  value.update();
  value.printAll();
}

错误是:

temp.cpp:24:10:错误:与"((B*)this)->B::a += ((B*)this)->B::at"中的"运算符+="不匹配

我做错了什么?

您定义的运算符是 A & operator+=(B &, A & ) ,而不是 A & operator+=(A &, A &) 。所以你已经定义了如何向B添加A,但没有定义如何将A添加到A。在class A的定义之后但在class B的定义之前尝试这样做:

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

但这种运算符更自然地定义为成员函数。

A& B::operator += (A& b)

方法

A & operator+=(B &, A & )

您只需要将operator +=(const A&b)添加到 A 类

class A
{
//....
    A& operator += (const A& b)
    {
       a += b.a;
       return *this;
    }
//....
};

非成员版本为:

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