In: Computer Science
#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;
//complex class
class complex
{
float real;
float img;
public :
// constructor
complex(float r=0,float i=0)
{
real = r;
img = i;
}
void display()
{
cout<<real<<"+i"<<img;
}
// fucntion to return the real part
float getReal()
{
return real;
}
// function to return the imaginary part
float getImg()
{
return img;
}
// function to over load the + operator
complex operator + (const complex &c2)
{
complex dummy;
dummy.real=real+c2.real;
dummy.img=img+c2.img;
return dummy;
}
// function to overload the - operator
complex operator - (const complex &c2)
{
complex dummy;
dummy.real=real-c2.real;
dummy.img=img-c2.img;
return dummy;
}
friend complex operator *
(float,complex);
friend complex operator * (complex,float);
//fucntion to overload the * operator for complex
multiplication
complex operator * (const complex &c)
{
complex dummy;
dummy.real = real*c.real -
img*c.img;
dummy.img = c.img*real +
c.real*img;
return dummy;
}
};
// complex to overload multiplication by scalar of the form
// x * (a + ib)
complex operator * (float f, complex c)
{
complex dummy;
dummy.real = c.real * f;
dummy.img *= c.img * f;
return dummy;
}
// complex to overload multiplication by scalar of the form
// (a + ib) * x
complex operator * (complex c, float f)
{
complex dummy;
dummy.real = c.real * f;
dummy.img = c.img * f;
return dummy;
}
int main()
{
complex t1(1,2),t2(2,3);
complex t3 = t1*2;
t3.display();
cout<<endl;
t3 = t1*t2;
t3.display();
cout<<endl;
t3=t1+t2;
t3.display();
cout<<endl;
return 0;
}