Overloads increment and decrement for the Box class, both the prefix and postfix forms - C++ Class

C++ examples for Class:Operator Overload

Description

Overloads increment and decrement for the Box class, both the prefix and postfix forms

Demo Code

#include <iostream>
using namespace std;
// A class that encapsulates 3-dimensional coordinates.
class Box {/*from   ww  w.jav a 2 s.  co  m*/
   int x, y, z; // 3-D coordinates
   public:
   Box() { x = y = z = 0; }
   Box(int i, int j, int k) { x = i; y = j; z = k; }
   // Overload ++ and --. Provide both prefix and postfix forms.
   Box operator++(); // prefix
   Box operator++(int notused); // postfix
   Box operator--(); // prefix
   Box operator--(int notused); // postfix
   // Let the overloaded inserter be a friend.
   friend ostream &operator<<(ostream &strm, Box op);
};
// Overload prefix ++ for Box.
Box Box::operator++() {
   x++;
   y++;
   z++;
   return *this;
}
// Overload postfix ++ for Box.
Box Box::operator++(int notused) {
   Box temp = *this;
   x++;
   y++;
   z++;
   return temp;
}
// Overload prefix -- for Box.
Box Box::operator--() {
   x--;
   y--;
   z--;
   return *this;
}
// Overload postfix -- for Box.
Box Box::operator--(int notused) {
   Box temp = *this;
   x--;
   y--;
   z--;
   return temp;
}
// The Box inserter is a non-member operator function.
ostream &operator<<(ostream &strm, Box op) {
   strm << op.x << ", " << op.y << ", " << op.z << endl;
   return strm;
}
int main()
{
   Box objA(1, 2, 3), objB(10, 10, 10), objC;
   cout << "Original value of objA: " << objA;
   cout << "Original value of objB: " << objB;
   // Demonstrate ++ and -- as stand-alone operations.
   ++objA;
   ++objB;
   cout << "++objA: " << objA;
   cout << "++objB: " << objB;
   --objA;
   --objB;
   cout << "--objA: " << objA;
   cout << "--objB: " << objB;
   objA++;
   objB++;
   cout << endl;
   cout << "objA++: " << objA;
   cout << "objB++: " << objB;
   objA--;
   objB--;
   cout << "objA--: " << objA;
   cout << "objB--: " << objB;
   cout << endl;
   // Now, demonstrate the difference between the prefix
   // and postfix forms of ++ and --.
   objC = objA++;
   cout << "After objC = objA++\n  objC: " << objC <<"  objA: "
   << objA << endl;
   objC = objB--;
   cout << "After objC = objB--\n  objC: " << objC <<"  objB: "
   << objB << endl;
   objC = ++objA;
   cout << "After objC = ++objA\n  objC: " << objC <<"  objA: "
   << objA << endl;
   objC = --objB;
   cout << "After objC = --objB\n  objC: " << objC <<"  objB: "
   << objB << endl;
   return 0;
}

Result


Related Tutorials