C++ Program For Arithmetic Operator Overloading for Object and Primitive

Free C++ course with real-time projects Start Now!!

Program 1

//Binary Operator overloading 
//(Arithmetic operator for object and primitive)
#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+(int x);
      Test operator-(int x);
      Test operator*(int x);
      Test operator/(int x);
      Test operator%(int x);
};
void Test::display()
{
    cout<<n;
}
Test Test::operator+(int x)
{
        Test temp;
        temp.n=n+x;
        return temp;       
}
Test Test::operator-(int x)
{
        Test temp;
        temp.n=n-x;
        return temp;       
}
Test Test::operator*(int x)
{
        Test temp;
        temp.n=n-x;
        return temp;       
}
Test Test::operator/(int x)
{
        Test temp;
        temp.n=n/x;
        return temp;       
}
Test Test::operator%(int x)
{
        Test temp;
        temp.n=n%x;
        return temp;       
}
int main()
{
      clrscr();
      Test T1(100);
      Test T2;
      cout<<"\nAddition ";
      T2=T1+50;  // T2=T1.operator+(50)
       T2.display();

      cout<<"\nSubtraction ";
      T2=T1-50;  // T2=T1.operator-(50)
      T2.display();
      cout<<"\nMultiplication ";
      T2=T1*50;  // T2=T1.operator*(50)
      T2.display();

       cout<<"\nDivision ";
      T2=T1/50;  // T2=T1.operator/(50)
      T2.display();
       cout<<"\nMod";
      T2=T1%50;  // T2=T1.operator%(50)
      T2.display();
      return 0;
}

 

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *