Addition,
Subtraction, Multiplication and Division of Complex Number using Operator
Overloading
Example :
#include<iostream.h>
class ComplexMath
{
private:
double real;
double im;
public:
void getData();
ComplexMath operator
+(ComplexMath);
ComplexMath operator
-(ComplexMath);
ComplexMath operator
/(ComplexMath);
ComplexMath operator
*(ComplexMath);
void Disp();
ComplexMath()
{
real=0;
im=0;
}
~ComplexMath(){}
};
void ComplexMath::getData()
{
ComplexMath z,y,x;
cout<<"\n\tEnter
Real : ";
cin>>real;
cout<<"\n\tEnter
Imaginary : ";
cin>>im;
}
ComplexMath ComplexMath::operator +(ComplexMath
C2)
{
ComplexMath C3;
C3.real=real+C2.real;
C3.im=im+C2.im;
return
C3;
}
ComplexMath ComplexMath::operator
-(ComplexMath C2)
{
ComplexMath
C3;
C3.real=real-C2.real;
C3.im=im-C2.im;
return C3;
}
ComplexMath
ComplexMath::operator /(ComplexMath C2)
{
float num =
(C2.real*C2.real)+(C2.im*C2.im);
ComplexMath C3;
C3.real=(real*C2.real)+(im*C2.im);
//Real numerator
C3.real=C3.real/num;
C3.im=(im*C2.real)-(real*C2.im);
C3.im=C3.im/num;
return C3;
}
ComplexMath
ComplexMath::operator *(ComplexMath C2)
{
ComplexMath
C3;
C3.real=real*C2.real+im*(-C2.im)*(-1);
//Real number of the numerator
C3.im=real*(-C2.im)+im*C2.real;
//Imaginary number of the numerator
return
C3;
}
void
ComplexMath::Disp()
{
cout<<real<<","<<im<<"i";
}
int
main()
{
ComplexMath
C1,C2,C3;
int
ch=0;
cout<<"\n\tEnter
First Complex No. ";
C1.getData();
cout<<"\n\tEnter
Second Complex No. ";
C2.getData();
while(ch!=5)
{
cout<<"\n\t1.
Addition";
cout<<"\n\t2.
Subtraction";
cout<<"\n\t3.
Multiplication";
cout<<"\n\t4.
Division";
cout<<"\n\t5.
Exit";
cout<<"\n\n\t\tChoice?
";
cin>>ch;
switch (ch)
{
case
1:
C3=C1+C2;
C1.Disp();
cout<<"
+ ";
C2.Disp();
cout<<"
= ";
C3.Disp();
break;
case
2:
C3=C1-C2;
C1.Disp();
cout<<"
- ";
C2.Disp();
cout<<"
= ";
C3.Disp();
break;
case
3:
C3=C1*C2;
C1.Disp();
cout<<"
* ";
C2.Disp();
cout<<" =
";
C3.Disp();
break;
case
4:
C3=C1/C2;
C1.Disp();
cout<<"
/ ";
C2.Disp();
cout<<"
= ";
C3.Disp();
break;
case
5:
break;
default:
cout<<"\n\n\t\tWrong
Input\n";
}
}
return 0;
}