Complex Numbers with Operator Overloading and Type Conversion - Computer Programming

Latest

C C++ Java Python Perl Programs Examples with Output -useful for Schools & College Students

Tuesday, October 26, 2010

Complex Numbers with Operator Overloading and Type Conversion


Program:
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class complex
{
private:
float real;
float imag;
public:
complex()
{
real=imag=0.0;
}
complex(int r,int i) //conversion constructor
{
real = r;
imag = i;
}
complex(double r, double i)//conversion constructor
{
real = r;
imag = i;
}
friend istream& operator>>(istream &, complex &);
friend ostream& operator<<(ostream &, complex &);
complex operator+(complex);
complex operator-(complex);
complex operator*(complex);
complex operator/(complex);
friend double condou(complex t); //complex–>double
};
double condou(complex t)
{
return t.real+t.imag;
}
istream& operator >>(istream &in, complex &c)
{
cout<<”\nReal Part:”;
in>>c.real;
cout<<”Imag Part:”;
in>>c.imag;
return in;
}
ostream& operator<<(ostream &out, complex &c)
{
if (c.imag<0)
out<<c.real<<c.imag<<”i”;
else
out<<c.real<<”+”<<c.imag<<”i”;
return out;
}
complex complex::operator+(complex c)
{
complex temp;
temp.real = real+c.real;
temp.imag = imag+c.imag;
return temp;
}
complex complex::operator-(complex c)
{
complex temp;
temp.real = real-c.real;
temp.imag = imag-c.imag;
return temp;
}
complex complex::operator*(complex c)
{
complex temp;
float t=c.real;
temp.real = real*c.real-imag*c.imag;
temp.imag = real*c.imag+imag*t;
return temp;
}
complex complex::operator/(complex c)
{
complex temp;
float qt;
float res=(imag*c.real-real*c.imag);
qt = c.real*c.real+c.imag*c.imag;
temp.real = (real*c.real+imag*c.imag)/qt;
temp.imag = res/qt;
return temp;
}
void main()
{
complex c1, c2, c3,c4(4,9),c5(3.23004,4.666304444);
double t;
clrscr();
t=condou(c5);
cout<<”\nEnter complex number 1: “;
cin>>c1;
cout<<”\nEnter complex number 2: “;
cin>>c2;
cout<<”\nEnter complex numbers are:”;
cout<<”\nComplex 1: “<<c1;
cout<<”\nComplex 2: “<<c2;
c3=c1+c2;
cout<<”\nResult of addition is:”<<c3;
c3=c1-c2;
cout<<”\nResult of subtraction is:”<<c3;
c3=c1*c2;
cout<<”\nResult of multiplication is:”<<c3;
c3=c1/c2;
cout<<”\nResult of division is:”<<c3;
cout<<”\nInteger–>complex:”<<c4;
cout<<”\nDouble–>complex:”<<c5;
cout<<”\nConverted to double”<<t;
getch();
}


No comments:

Post a Comment