C++ Program For Binary Operator Overloading for Arithmetic Operator
Master C++ with Real-time Projects and Kickstart Your Career Start Now!!
Program 1
//Binary Operator overloading (Arithmetic operator)
#include<iostream>
#define clrscr() system("cls")
using namespace std;
class Test
{
int n;
public:
Test(int n)
{
this->n=n;
}
Test(){}
void display();
Test operator+(Test &k);
Test operator-(Test &k);
Test operator*(Test &k);
Test operator/(Test &k);
Test operator%(Test &k);
};
Test Test::operator+(Test &k)
{
Test temp;
temp.n=n+k.n;
return temp;
}
Test Test::operator-(Test &k)
{
Test temp;
temp.n=n-k.n;
return temp;
}
Test Test::operator*(Test &k)
{
Test temp;
temp.n=n*k.n;
return temp;
}
Test Test::operator/(Test &k)
{
Test temp;
temp.n=n/k.n;
return temp;
}
Test Test::operator%(Test &k)
{
Test temp;
temp.n=n%k.n;
return temp;
}
void Test::display()
{
cout<<"\n "<<n;
}
int main()
{
clrscr();
int x,y;
cout<<"Enter two numbers: ";
cin>>x>>y;
Test T1(x);
Test T2(y);
Test T3;
cout<<"\n Object Arithmetic operations: ";
cout<<"\nAddition";
T3=T1+T2;
T3.display();
cout<<"\nSubtraction";
T3=T1-T2;
T3.display();
cout<<"\nMultiplication";
T3=T1*T2;
T3.display();
cout<<"\ndivision";
T3=T1/T2;
T3.display();
cout<<"\nMod";
T3=T1%T2;
T3.display();
return 0;
}
// T1+T2 T1.operator+(T2)
// T1-T2 T1.operator-(T2)
// T1*T2 T1.operator*(T2)
// T1/T2 T1.operator/(T2)
We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google

