I am overloading 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? Everywhere it is indicated exactly such an overload signature of this operator.

    2 answers 2

    Each non-static member function of a class has an implicit parameter that takes the value of 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 access to closed 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 refer to private or protected members of the class.

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

     MyClass operator+( const MyClass &b) const { ... return this->value + b.value; } 
    • Thank. I remembered that this applies, but it was confusing that 2 parameters are written everywhere. Now everything is clear. - LNK Nov.

    In class, it must be reloaded with one argument. The second argument is an object of the class itself.

    If you create it as a free function (outside the class) - that's right, it is this signature that should be.