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?
No. Since the LHS is a
const A&and RHS is anint, it will call*as you’ve only provided the non-
constversionconst A& operator+( int m ), the compiler will complain.*: Or
operator+(const int& rhs) constoroperator+(float rhs) const… The crucial point is that it must be aconstmethod.