overloaded 'operator+' must be a unary or binary operator error

空扰寡人 提交于 2019-12-13 12:56:39

问题


Following the advice given in this answer, I have overloaded the + operator in my simple Point class as follows (the += overload works fine).

Point operator+ (Point p1, const Point& p2)
{
    return std::move(p1 += p2);
}

But I get an error saying

overloaded 'operator+' must be a unary or binary operator (has 3 parameters)

What is wrong?


回答1:


It sounds like you have declared your operator as a member function. A member function takes an implicit first parameter, meaning your operator now takes three parameters. You can fix this by making it a non-member function.

In any case, it is preferable to declare it as a non-member, to ensure symmetry between the LHS and the RHS of the operation.

As for std::move, it is in the <utility> header. Although I can't see the reason to use it here.




回答2:


You want to do either:

// Perform (*this + right)
Point operator+ (Point & right)

or

// Perform (left + right)  Friend functions have no "this".
friend Point operator+ (const Point &left, const Point& right)



回答3:


You made the operator a member function, meaning it actually has three parameters when you include the implicit first this parameter.

Either:

  • Use *this rather than p1 and get rid of that first parameter, or
  • Make the operator overload a free function (instead of a member) — this is preferred.


来源:https://stackoverflow.com/questions/13554320/overloaded-operator-must-be-a-unary-or-binary-operator-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!