Question on overloading operator+
c++, operator-overloading
Solution
which is then passed to "const A& operator+( int m )" if I'm not mistaken
No. Since the LHS is a `const A&` and RHS is an `int`, it will call*
[anyType] operator+ (int rhs) const
// ^^^^^ note the const here.
as you've only provided the non-`const` version `const A& operator+( int m )`, the compiler will complain.
*: Or `operator+(const int& rhs) const` or `operator+(float rhs) const`... The crucial point is that it must be a `const` method.
Problem
Consider the following code: ``` class A { public: A& operator=( const A& ); const A& operator+( const A& ); const A& operator+( int m ); }; int main() { A a; a = ( a + a ) + 5; // error: binary '+' : no operator found which takes a left-hand operand of type 'const A' } ``` Can anyone explain why the above is returned as an error? "`( a + a )`" calls "`const A& operator+( const A& )`" and returns a constant reference which is then passed to "`const A& operator+( int m )`" if I'm not mistaken. How can one fix the above error (without creating a global binary operator+ or a constructor that accepts an int) such that the statement inside `main()` is allowed?