Overloading operators (+=, -=, *=, /=, %=)
Example:1
Add two objects using the overloaded operator “+=”.
// to overload += // add two objects using "+=" operator //without friend function #include<iostream> #include<conio.h> using namespace std; class sample { int a; public: sample(); sample(int n); void get(); void disp(); void operator+=(sample s); }; sample::sample() { a=0; } sample::sample(int n) { a=n; } void sample::get() { cout<<"Enter the value of a "; cin>>a; } void sample::disp() { cout<<"a= "<<a<<endl; } void sample::operator+=(sample s) { a+=s.a; } int main() { sample s1,s2; s1.get();s2.get(); s1.disp();s2.disp(); //+= cout<<"sum"<<endl; s2+=s1;//s2.operator+=(s1); s2.disp(); getch(); return(0); }
Output:
Enter the value of a 10
Enter the value of a 20
a= 10
a= 20
sum
a= 30
Example:2
overloading operator “-=”.
// to overload -= // add two objects using "-=" operator //without friend function #include<iostream> #include<conio.h> using namespace std; class sample { int a; public: sample(); sample(int n); void get(); void disp(); void operator-=(sample s); }; sample::sample() { a=0; } sample::sample(int n) { a=n; } void sample::get() { cout<<"Enter the value of a "; cin>>a; } void sample::disp() { cout<<"a= "<<a<<endl; } void sample::operator-=(sample s) { a-=s.a; } int main() { sample s1,s2; s1.get();s2.get(); s1.disp();s2.disp(); //-= cout<<"Difference"<<endl; s2-=s1;//s2.operator-=(s1); s2.disp(); getch(); return(0); }
Output:
Enter the value of a 25
Enter the value of a 6
a= 25
a= 6
sum
a= -19
Example:3
overloading operator “*=”.
// to overload *= // add two objects using "*=" operator //without friend function #include<iostream> #include<conio.h> using namespace std; class sample { int a; public: sample(); sample(int n); void get(); void disp(); void operator*=(sample s); }; sample::sample() { a=0; } sample::sample(int n) { a=n; } void sample::get() { cout<<"Enter the value of a "; cin>>a; } void sample::disp() { cout<<"a= "<<a<<endl; } void sample::operator*=(sample s) { a*=s.a; } int main() { sample s1,s2; s1.get();s2.get(); s1.disp();s2.disp(); //*= cout<<"Product"<<endl; s2*=s1;//s2.operator*=(s1); s2.disp(); getch(); return(0); }
Output:
Enter the value of a 10
Enter the value of a 25
a= 10
a= 25
Product
a= 250