This is a sample program on operator overloading. Using operator overloading, here we add two complex numbers.
#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
class complex
{
private:
double real, img;
public:
complex ( )
{
real = img = 0.0;
}
void read ( )
{
cout<<"\n Enter Real & Imaginary Part: ";
cin >> real >> img;
}
complex operator + (complex cc2)
{
complex temp;
temp.real = real + cc2.real;
temp.img = img + cc2.img;
return (temp);
}
void show ( )
{
cout<<"The Sum Is: "<<'\n';
if (img > 0)
cout<<real << "+" << img << "i" << endl;
else
cout << real << img << "i" << endl;
}
};
int main ( )
{
clrscr ( );
complex c1, c2, c3;
cout << "\n Enter Complex Number C1";
c1.read ( );
cout << "\n Enter Complex Number C2";
c2.read ( );
c3 = c1 + c2;
c3.show ( );
getch ( );
return 0;
}
OUTPUT:
Enter Complex Number C1
Enter Real & Imaginary Part:
5
6
Enter complex number C2
Enter Real & Imaginary Part:
2
4
The Sum Is: 7+10i
Comments
Post a Comment
Please share your opinions and suggestions or your experience in the comments section. This way we can all help each other...
Experienced guys can share their resumes at admin@interview-made-easy.com