Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 299
learnvst Avatar asked Nov 25 '12 18:11

learnvst


People also ask

Can we overload unary operator to work with binary operator?

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.

Which unary operator Cannot be overloaded?

Operators that cannot be overloaded are . . * :: ?: Operator cannot be used to overload when declaring that function as friend function = () [] ->.

Can binary operator be overloaded in C++?

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?

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.


2 Answers

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.

like image 179
juanchopanza Avatar answered Oct 25 '22 08:10

juanchopanza


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)
like image 20
Drew Dormann Avatar answered Oct 25 '22 07:10

Drew Dormann