C++ Program For Arithmetic Operator Overloading for Primitive and Object
Master C++ with Real-time Projects and Kickstart Your Career Start Now!!
Program 1
//Binary Operator overloading
//(Arithmetic operator for primitive and Object )
#include<iostream>
#define clrscr() system("cls")
using namespace std;
class Test
{
int n;
public:
Test(int n)
{
this->n=n;
}
Test(){}
friend Test operator+(int x,Test &k);
friend Test operator-(int x,Test &k);
friend Test operator*(int x,Test &k);
friend Test operator/(int x,Test &k);
friend Test operator%(int x,Test &k);
void display();
};
void Test::display()
{
cout<<"\n "<<n;
}
Test operator+(int x,Test &k)
{
Test temp;
temp.n=x+k.n;
return temp;
}
Test operator-(int x,Test &k)
{
Test temp;
temp.n=x-k.n;
return temp;
}
Test operator/(int x,Test &k)
{
Test temp;
temp.n=x/k.n;
return temp;
}
Test operator*(int x,Test &k)
{
Test temp;
temp.n=x*k.n;
return temp;
}
Test operator%(int x,Test &k)
{
Test temp;
temp.n=x%k.n;
return temp;
}
int main()
{
clrscr();
Test T1(50);
Test T2;
T2=500+T1; // T2=operator+(500,T1)
T2.display();
T2=500-T1; // T2=operator-(500,T1)
T2.display();
T2=500*T1; // T2=operator*(500,T1)
T2.display();
T2=500/T1; // T2=operator/(500,T1)
T2.display();
T2=500%T1; // T2=operator%(500,T1)
T2.display();
}
Did we exceed your expectations?
If Yes, share your valuable feedback on Google

