C++ examples for Class:Operator Overload
Overloading the Increment and Decrement Operators
#include <iostream> using namespace std; class MyClass {/* w ww . j a v a 2 s. c o m*/ public: MyClass() : score_(0) {} MyClass(int i) : score_(i) {} MyClass& operator++() { // prefix ++score_; return(*this); } const MyClass operator++(int) { // postfix MyClass tmp(*this); ++(*this); // Take advantage of the prefix operator return(tmp); } MyClass& operator--() { --score_; return(*this); } const MyClass operator--(int x) { MyClass tmp(*this); --(*this); return(tmp); } int getScore() const {return(score_);} private: int score_; }; int main() { MyClass player1(50); player1++; ++player1; // score_ = 52 cout << "Score = " << player1.getScore() << '\n'; (--player1)--; // score_ = 50 cout << "Score = " << player1.getScore() << '\n'; }