Question #332576

Create a class of complex number having two attribute real and imaginary. Write a function to add two complex number and print the result. You need to write parameterized constructor. In main, create two objects of complex number, call the addition function and print the result.


Expert's answer

#include <iostream>
using namespace std;

class Complex {

    float real;
    float imaginary;
    
public:
    Complex() {
     real=0;
     imaginary=0;    
    }
    Complex(float real, float imaginary)     {
        this->real = real;
        this->imaginary = imaginary;
    }
    Complex operator+(const Complex &) const;    //addition
    
    void display() {
        if (imaginary>=0)
            cout << real << " + " << imaginary << "i" << endl <<endl;
        else  
            cout << real  << " + (" << imaginary << "i)" << endl <<endl;
    }
};
   //Overloaded addition operator
    Complex Complex::operator+(const Complex &operand2) const
    {
        return Complex(real + operand2.real, imaginary +operand2.imaginary);

    };
 
int main()
{
    Complex z1(10, 35), z2(8, -45), z3;
    z1.display();
    z2.display();

    z3 = z1+z2;

    z3.display();
     
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS