Operator overloading in oop
Operator overloading in oop
Conclusion: Hence, we have studied, used and demonstrated use of binary operator
overloading and insertion-extraction operator overloading using friend function.
PROGRAM
//Program to demonstrate various operations on Complex class
#include<iostream>
using namespace std;
class Complex
{
float real,img;
public:
//Constructor
Complex()
{
real=0;
img=0;
}
Complex(float a,float b)
{
real=a;
img=b;
}
//Addition of two complex numbers
Complex operator+(Complex c1)
{
Complex temp;
temp.real=real+c1.real;
temp.img=img+c1.img;
return temp;
}
//Subtraction of two complex numbers
Complex operator-(Complex c1)
{
Complex temp;
temp.real=real-c1.real;
temp.img=img-c1.img;
return temp;
}
//Multiplication of two complex numbers
Complex operator*(Complex c1)
{
Complex temp;
temp.real=(real*c1.real)-(img*c1.img);
temp.img=(img*c1.real)+(real*c1.img);
return temp;
}
};
int main()
{
Complex c1,c2,c3;
int choice;
char ans;
do
{
cout<<"\n************* MENU ************\n";
cout<<"\n\t1.Addition\n\t2.Subtraction\n\t3.Multiplication\n";
cout<<"\n\nEnter your choice: ";
cin>>choice;
cout<< "Enter real and img part of first complex number\n";
cin>>c1;
cout<< "Enter real and img part of second complex number\n";
cin>>c2;
switch(choice)
{
case 1:
c3=c1+c2;
cout<<"\n\nAddition is: ";
cout<<c3;
break;
case 2:
c3=c1-c2;
cout<<"\n\nSubtraction is: ";
cout<<c3;
break;
case 3:
c3=c1*c2;
cout<<"\n\nMultiplication is: ";
cout<<c3;
default:
cout<<"\nWrong choice";
}
cout<<"\nDo you want to continue?(y/n): ";
cin>>ans;
}while(ans=='y' || ans=='Y');
return 0;
}