问题
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 thanp1
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