Example of an Overloaded Operator


/************************************************************************
*

In the following example, a class called complx is defined to model complex numbers, and the + (plus) operator is redefined in this class to add two complex numbers.

                                                                        *
************************************************************************/

// This example illustrates overloading the plus (+) operator.

#include <iostream.h>
class complx
{
      double real,
             imag;
public:
      complx( double real = 0., double imag = 0.); // constructor
      complx operator+(const complx&) const;       // operator+()
};
// define constructor
complx::complx( double r, double i )
{
      real = r; imag = i;
}
// define overloaded + (plus) operator
complx complx::operator+ (const complx& c) const
{
      complx result;
      result.real = (this->real + c.real);
      result.imag = (this->imag + c.imag);
      return result;
}
void main()
{
      complx x(4,4);
      complx y(6,6);
      complx z = x + y; // calls complx::operator+()
}

/************************************************************************
*

For the class complx, described above, you can call the overloaded + (plus) operator either implicitly or explicitly as shown below.

                                                                        *
************************************************************************/

// This example shows implicit and explicit calls
// to an overloaded plus (+) operator.

class complx
{
      double real,
             imag;
public:
      complx( double real = 0., double imag = 0.);
      complx operator+(const complx&) const;
};
//      .
//      .
//      .
void main()
{
      complx x(4,4);
      complx y(6,6);
      complx u = x.operator+(y); // explicit call
      complx z = x + y;          // implicit call to complx::operator+()
}