c++ – What is the error when overloading the + operator?

Question:

I overload binary + in my class:

MyClass operator+(const MyClass &a, const MyClass &b) {
    ...
    return a.value + b.value;
}

I get an error бинарный оператор + имеет слишком много параметров . What is the problem? This operator overload signature is specified everywhere.

Answer:

Each non-static member function of a class has an implicit parameter that receives the value this , that is, a pointer to the class object itself.

You need to either define this operator in the class as a friendly function (if you need to access private or protected members of the class), for example

friend MyClass operator+(const MyClass &a, const MyClass &b) {
    ...
    return a.value + b.value;
}

Or declare it as a normal function outside the class, if you do not need to access private or protected members of the class.

Or make the operator a member function of the class, but with one explicit parameter

MyClass operator+( const MyClass &b) const {
    ...
    return this->value + b.value;
}
Scroll to Top