【问题标题】:non member += overloading in C++C++ 中的非成员 += 重载
【发布时间】:2013-01-29 23:17:41
【问题描述】:
#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 中的 'operator+=' 不匹配'

我做错了什么?

【问题讨论】:

  • 您的重载占用了B 的左侧,而不是A
  • 有什么困惑?您显然没有为 A 类定义 operator+=...

标签: c++ overloading operator-keyword


【解决方案1】:

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

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

但是这种操作符更自然的定义为成员函数。

【讨论】:

  • 但是我不能让它只是B类的成员。本质上A是一个结构。
  • 我可以让这个函数成为我命名空间的一部分,所以我会没事的,但我不能在 B 类中这样做吗?
  • @user1576929,如果是B的成员,左边必须是B。没有例外。
  • 不,如果它是B 的成员,那么它隐式定义了如何对B 进行操作,而不是对A。而你正在做a += at,它试图增加a,这是一个A,通过at,这也是一个A
【解决方案2】:
A& B::operator += (A& b)

意思

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

您只需将operator +=(const A&amp;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; }

【讨论】:

  • 我同意最好通过成员函数来完成,但他要求以非成员的方式来做。
  • 是的,我不能编辑 A。它是 ROS 的一部分。我不想碰那个。 B 是我的函数,我希望所有重载只影响 B 中 A 的对象。
猜你喜欢
  • 1970-01-01
  • 2011-07-19
  • 1970-01-01
  • 2011-06-05
  • 1970-01-01
  • 2014-11-04
  • 2013-08-30
  • 1970-01-01
相关资源
最近更新 更多