Aim:
To write a C++ program to implement the concept of Binary operator overloading.
Description:
- The binary operators take two arguments and following are the examples of Binary operators.
- You use binary operators very frequently like addition (+) operator, subtraction (-) operator and division (/) operator.
Following example explains how addition (+) operator can be overloaded. Similar way, you can overload subtraction (-) and division (/) operators.
Algorithm:
- Start the program.
- Declare the class.
- Declare the variables and its member function.
- Using the function getvalue () to get the two numbers.
- Define the function operator + () to add two complex numbers.
- Define the function operator – () to subtract two complex numbers.
- Define the display function.
- Declare the class objects obj1, obj2 and result.
- Call the function getvalue using obj1 and obj2
- Calculate the value for the object result by calling the function operator + and Operator – Obj2 and result.
- Return the values.
- Call the display function using obj1 and
- Stop the program
Program:
include<iostream> using namespace std; class Complex { private: int real; int imag; public: Complex():real(0),imag(0){} Complex(int a,int b):real(a),imag(b){} Complex operator +(Complex); Complex operator - (Complex); void disp(); }; Complex Complex::operator +(Complex d) { Complex temp; temp.real=real+d.real; temp.imag=imag+d.imag; return temp; } Complex Complex::operator -(Complex d) { Complex temp; temp.real=real-d.real; temp.imag=imag-d.imag; return temp; } void Complex::disp() { cout<<real; if(imag>=0) { cout<<"+"<<imag<<"i"; } else{ cout<<"-"<<imag<<"i"; } cout<<endl; } int main() { int a,b,c,d; Complex z; cout<<"ENTER THE TWO COMPLEX NUMBERS \n"; cin>>a>>b>>c>>d; Complex x(a,b),v(c,d); x.disp(); v.disp(); cout<<"\nSUM OF TWO COMPLEX :"; z=x+v; z.disp(); z=x-v; cout<<"\nDIFFERENCE OF TWO COMPLEX :"; z.disp(); return 0; }
Execution:
INPUT : ENTER THE TWO COMPLEX NUMBERS : 5 7 3 1 OUTPUT : SUM OF THE COMPLEX: 8+8i DIFFERENCE OF TWO COMPLEX: 2+6i
Result:
Thus, the Implement the Concept of Binary Operator Overloading was executed successfully.