Question about operator overload +

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 returns as an error?

" ( a + a )" calls " const A& operator+( const A& )" and returns a permalink, which is then passed to " const A& operator+( int m )" if I am not mistaken.

How can I eliminate the above error (without creating a global binary + operator or constructor that accepts int) to allow the statement inside main()?

+3
source share
6 answers

which is then passed to "const A & operator + (int m)" if I'm not mistaken

. LHS const A&, RHS - int, *

[anyType] operator+ (int rhs) const
//                            ^^^^^ note the const here.

const const A& operator+( int m ), .

*: operator+(const int& rhs) const operator+(float rhs) const... , const.

+7

operator+ , :

// as member function
A operator+(const A& other);

// as free function
A operator+(const A& left, const A& right);

, " , const A& operator+( int m )". const, , const (.. const A& operator+( int m ) const).

, operator+. , ? + , . , . , . *this , operator+ operator +=.

+6

. const. , - .

+2

, (a+a) rvalue ( ). - r-, - const. , , , operator+ alwasys .

:

A operator+( const A& ) const;
A operator+( int m ) const;

, , , :

class A { ... };

A operator+(const A& lhs, const A& rhs);
A operator+(const A& lhs, int rhs);

operator+=, :

class A {
  public:
   A& operator+=(const A& rhs);
   A& operator+=(int rhs);
};

inline A operator+(A lhs, const A& rhs) // note: lhs is passed by copy now
{
  lhs += rhs;
  return lhs;
}
A operator+(A lhs, int rhs) // note: lhs is passed by copy now
{
  lhs += rhs;
  return lhs;
}
+1

const:

const A& operator+( int m ) const;

+1

const A& operator+( const A& ) , non-const member const A& operator+( int m ) const.   A& operator+( const A& ), const A& operator+( int m )const;   , , - . , ++ 0x r-. i A operator+(const A& rhs)const A&& operator+(const A& rhs)const;

+1

Source: https://habr.com/ru/post/1735769/


All Articles