Write a program to perform addition of two complex numbers using constructor overloading.
The first constructor which takes no argument is used to create objects which are not initialized, second which takes one argument is used to initialize real and imaginary parts to equal values and third which takes two argument is used to initialize real and imaginary to two different values.
# include<iostream>
using namespace std;
class Complex
{
private:
int realPart,imagPart;
public:
Complex() { } //First constructor
//Second Constructor
Complex(int number) {
realPart=imagPart=number;
}
//Third Constructor
Complex(int real,int imag)
{
realPart=real;
imagPart=imag;
}
void print()
{
cout<<realPart<<"+"<<imagPart<<"i."<<endl;
}
Complex sum(Complex complex1, Complex complex2){
Complex comp;
comp.realPart = complex1.realPart + complex2.realPart;
comp.imagPart = complex1.imagPart + complex2.imagPart;
return comp;
}
};
int main()
{
Complex c1(9,8);
cout<<"First Complex Number is: "; c1.print();
Complex c2(3,4);
cout<<"Second Complex Number is: "; c2.print();
Complex c3;
c3 = c3.sum(c1, c2);
cout<<"The result of adding the two complex numbers: ";
c3.print();
}
Comments
Leave a comment