Example:5
Overloading decrement operator (- -) (Postfix form)
// to overload -- operator (as postfix) //post increment #include<iostream> #include<conio.h> using namespace std; class sample { int a; public: sample();//defa sample(int n); //para void get(); void disp(); void operator--(int); }; 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--(int) { a=a-1; } int main() { sample s1,s2; s1.get();s2.get(); s1.disp();s2.disp(); s1--;//s1.operator++(); s1--; s2--; s1.disp();s2.disp(); getch(); return(0); }
Output:
Enter the value of a 10
Enter the value of a 20
a= 10
a= 20
a= 8
a= 19
Example:6
Overloading increment operator (++) with friend function
// to overload ++ operator //With friend function #include<iostream> #include<conio.h> using namespace std; class sample { int a; public: sample();//defa sample(int n); //para void get(); void disp(); friend sample operator++(sample t); }; 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; } sample operator++(sample t) { t.a=t.a+1; return(t); } int main() { sample s1,s2; s1.get(); s1.disp(); s2=++s1;//s2=operator++(s1); s2.disp(); getch(); return(0); }
Output:
Enter the value of a 10
a= 10
a= 11
Example:7
Overloading increment operator (- -) with friend function
// to overload -- operator ( with friend function) //With friend function #include<iostream> #include<conio.h> using namespace std; class sample { int a; public: sample();//defa sample(int n); //para void get(); void disp(); friend sample operator--(sample t); }; 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; } sample operator--(sample t) { t.a=t.a-1; return(t); } int main() { sample s1,s2; s1.get(); s1.disp(); s2=--s1;//s2=operator--(s1); s2.disp(); getch(); return(0); }
Output: