C ++ - How to overload the + = operator?

Given the following piece of code,

class Num
{
public:
    Num(int iNumber = 0) : m_iNumber(iNumber) {}

    Num operator+=(const Num& rhs)
    {
        this->m_iNumber = (this->m_iNumber + rhs.m_iNumber);
        return *this;
    }
private:
    int m_iNumber;
};

//===========================================================
int _tmain(int argc, _TCHAR* argv[])
{
    Num a(10);

    Num b(100);

    b += a;

    return 0;
}

I would like to know how to properly reload operator+=.

Questions:

  • How to determine the signature of this operator? In particular, what should be used for the return value?

  • How to implement a function body?

  • How to use this overload operator?

I have provided the solution as above, but I have problems that this is not true.

+5
source share
5 answers

Returning by reference would be better

Num& operator+=(const Num& rhs){

      this->m_iNumber += rhs.m_iNumber;
      return *this;
}
+16
source

If you follow this Wikibook , you will find these answers with an example:

  • Type& operator+=(const Type& right) - correct signature.
  • You did it right.
  • , , . .;)

, ( ) -.

+5

(operator = operator @= @)

Class& operator @= (const Class& rhs);

, const ( ), . , , , :

(a += b) += c;

, ints .

, , , . , , , , . , -

a += a;

a.operator+= (a);

, , . ( operator=), , .

, operator += , . += .

, !

+4

: http://codepad.org/PVhQw9sc.

  • . , , int, Num& *this.
  • .
  • .
+2

, . , . , .

.

+1

All Articles