Search code examples
c++c++11operator-overloading

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


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?


Solution

  • 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.