Search This Blog

program to perform multiplication of two complex numbers using operator overloading in c++

C++ allows you to specify more than one definition for a function name or anoperator in the same scope, which is called function overloading andoperator overloading respectively.
An overloaded declaration is a declaration that had been declared with the same name as a previously declared declaration in the same scope, except that both declarations have different arguments and obviously different definition (implementation).
When you call an overloaded function or operator, the compiler determines the most appropriate definition to use by comparing the argument types you used to call the function or operator with the parameter types specified in the definitions. The process of selecting the most appropriate overloaded function or operator is called overload resolution.Below is a program which shows operator overloading :
//SOurce code:
 ‪#‎include‬<iostream.h>  
 #include<stdlib.h>  
 #include<conio.h>  
 class complex  
 {  
 float a,b;  
 public:  
 complex()  
 {a=0.0;b=0.0;}  
 ~complex()  
 { }  
 complex operator +(complex);  
 complex operator *(complex);  
 complex operator /(complex);  
 complex operator -(complex);  
 void input()  
 {  
 cout<<"\n Enter real part: ";cin>>a;  
 cout<<"\n Enter imag. part: ";cin>>b;  
 }  
 void show()  
 {  
 cout<<"\n The complex number = ";  
 cout<<a<<"+("<<b<<")i"<<endl;  
 }  
 };  
 complex complex::operator+(complex y)  
 {  
 complex x;  
 x.a=a+y.a;  
 x.b=b+y.b;  
 return x;  
 }  
 complex complex::operator-(complex y)  
 {  
 complex x;  
 x.a=a-y.a;  
 x.b=b-y.b;  
 return x;  
 }  
 complex complex::operator*(complex y)  
 {  
 complex x;  
 x.a=a*y.a-b*y.b;  
 x.b=a*y.b+b*y.a;  
 return x;  
 }  
 complex complex::operator / (complex y)  
 {  
 complex x;  
 float p;  
 p=y.a*y.a+y.b*y.b;  
 x.a=(a*y.a+b*y.b)/p;  
 x.b=(b*y.a-a*y.b)/p;  
 return x;  
 }  
 void main()  
 {  
 char ch; int n;  
 complex c1,c2,c3,c4,c5,c6;  
 clrscr();  
 c1.input();  
 c2.input();  
 c1.show();  
 c2.show();  
 do{  
 cout<<"\n Enter operation symbol to perform \n any operation on given two complex numberslike (+,-,*,/):";  
 cout<<"\n Enter an option: ";  
 cin>>ch;  
 if(ch=='+')  
 n=1;  
 else if(ch=='-')  
 n=2;  
 else if(ch=='*')  
 n=3;  
 else if(ch=='/')  
 n=4;  
 else {  
 cout<<"\nwrong input\n";  
 exit(1);  
 }  
 switch(n) {  
 case 1: {  
 c3=c1+c2;  
 c3.show();  
 break; }  
 case 2: {  
 c4=c1-c2;  
 c4.show();  
 break; }  
 case 3:{  
 c5=c1*c2;  
 c5.show();  
 break; }  
 case 4: {  
 c6=c1/c2;  
 c6.show();  
 break; } }  
 cout<<"\n do you want to continue,y/n: ";  
 cin>>ch;  
 }while(ch!='n');  
 getch();  
 }  
OUTPUT:


No comments:

Post a Comment

leave a comment here