C++ program to overload addition operator to add two complex numbers


Suppose we have a complex number class with real and imaginary part. We shall have to overload the addition (+) operator to add two complex number. We also have to define a function to return complex number in proper representation.

So, if the input is like c1 = 8 - 5i, c2 = 2 + 3i, then the output will be 10 - 2i.

To solve this, we will follow these steps −

  • Overload the + operator and take another complex number c2 as argument

  • define a complex number called ret whose real and imag are 0

  • real of ret := own real + real of c2

  • imag of ret := own imag + imag of c2

  • return ret

Example

Let us see the following implementation to get better understanding −

#include <iostream>
#include <sstream>
#include <cmath>
using namespace std;
class Complex {
    private:
        int real, imag;
    public:
    Complex(){
        real = imag = 0;    
    }
    Complex (int r, int i){
        real = r;
        imag = i;
    }
    string to_string(){
        stringstream ss;
        if(imag >= 0)
            ss << "(" << real << " + " << imag << "i)";
        else
            ss << "(" << real << " - " << abs(imag) << "i)";
        return ss.str();
    }
    Complex operator+(Complex c2){
        Complex ret;
        ret.real = real + c2.real;
        ret.imag = imag + c2.imag;
        return ret;
    }
};
int main(){
    Complex c1(8,-5), c2(2,3);
    Complex res = c1 + c2;
    cout << res.to_string();
}

Input

c1(8,-5), c2(2,3)

Output

(10 - 2i)

Updated on: 31-Oct-2023

24K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements