C++ Operator Overload binary += operator (compound assignment operator)

Introduction

Let us overload a binary operator +=:

#include <iostream> 
class MyClass /* ww w.  j  ava2 s .  c  o  m*/
{ 
private: 
    int x; 
    double d; 
public: 
    MyClass(int xx, double dd) 
         : x{ xx }, d{ dd } 
    { 
    } 

    MyClass& operator+=(const MyClass& rhs) 
    { 
        this->x += rhs.x; 
        this->d += rhs.d; 
        return *this; 
    } 
}; 

int main() 
{ 
    MyClass myobject{ 1, 1.0 }; 
    MyClass mysecondobject{ 2, 2.0 }; 
    myobject += mysecondobject; 
    std::cout << "Used the overloaded += operator."; 
} 

Now, myobject member field x has a value of 3, and a member field d has a value of 3.0.




PreviousNext

Related