23 Nov 2019

  • November 23, 2019
  • Amitraj
*Overloading Binary Operators:-

-> 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.


// C++ program to demonstrate overloading Binary operator.


#include<iostream>
using namespace std;
class complex
{
float x;
float y;
public:
complex()   // default constructor
{
}
complex(float real,float image) // Parameterized constructor
{
x=real;y=image;
}
complex operator +(complex c)
{
complex temp;
temp.x= x+c.x;
temp.y= y+c.y;
return temp;
}
void display()
{
cout<<x<<"+j"<<y<<endl;
}
};

int main()
{
complex c1,c2,c3;
c1=complex(2.5,3.5);
c2=complex(1.6,2.7);
c3=c1+c2;
cout<<"c1="; c1.display();
cout<<"c2="; c2.display();
cout<<"c3="; c3.display();
return 0;

}

OUTPUT:

c1=2.5+j3.5
c2=1.6+j2.7

c3=4.1+j6.2



Translate

Popular Posts