Overload plus operator (+) for Complex class - C++ Class

C++ examples for Class:Operator Overload

Description

Overload plus operator (+) for Complex class

Demo Code

#include <iostream>
#include <iomanip>
using namespace std;
// declaration section
class Complex/* www.j a v  a2 s  . co  m*/
{
   private:
   double realPart;       // declare realPart as a double variable
   double imaginaryPart;   // declare imaginaryPart as a double variable
   public:
   Complex(double real = 0.0, double imag = 0.0)    // inline constructor
   {
      realPart = real;
      imaginaryPart = imag;
   }
   void showComplexValues();                       // accessor prototype
   void assignNewValues(double real, double imag);   // inline mutator
   Complex operator+(const Complex&);  // prototype for the addition operator
}; 
// implementation section
void Complex::showComplexValues()  // accessor
{
   char sign = '+';
   if (imaginaryPart < 0)
      sign = '-';
   cout << realPart << ' ' << sign << ' ' << abs(imaginaryPart) << 'i';
}
Complex Complex::operator+(const Complex& complex2)
{
   Complex temp;
   temp.realPart = realPart + complex2.realPart;
   temp.imaginaryPart = imaginaryPart + complex2.imaginaryPart;
   return temp;
}
int main()
{
   Complex a(2.3, 10.5), b(6.3, 19.2), c;  // declare three objects
   cout << "Complex number a is ";
   a.showComplexValues();
   cout << "\nComplex number b is ";
   b.showComplexValues();
   c = a + b;   // add two complex numbers
   cout << "\n\nThe sum of a and b: ";
   c.showComplexValues();
   return 0;
}

Result


Related Tutorials