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?
Rules of operator overloading We can overload an operator as its type only i.e., a unary operator cannot be overloaded as a binary operator and vice versa. We can't overload operators that are not a part of C++. We can perform operator overloading only in user-defined classes.
Operators that cannot be overloaded are . . * :: ?: Operator cannot be used to overload when declaring that function as friend function = () [] ->.
A binary operator can be overloaded as a non-static member function with one parameter or as a non-member function with two parameters (one of those parameters must be either a class object or a reference to a class object).
Which is the correct statement about operator overloading? Explanation: Both arithmetic and non-arithmetic operators can be overloaded. The precedence and associativity of operators remains the same after and before operator overloading.
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.
You want to do either:
// Member function, performs (*this + right)
Point operator+ (Point & right)
or
// Free function, performs (left + right)
Point operator+ (const Point &left, const Point& right)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With