c++operator-overloading

How can I overload the operator++ in two different ways for postfix a++ and prefix ++a?


How can I overload the operator++ in two different ways for postfix a++ and prefix ++a?


Solution

  • Should look like this:

    class Number 
    {
        public:
            Number& operator++ ()     // prefix ++
            {
               // Do work on this.   (increment your object here)
               return *this;
            }
    
            // You want to make the ++ operator work like the standard operators
            // The simple way to do this is to implement postfix in terms of prefix.
            //
            Number  operator++ (int)  // postfix ++
            {
               Number result(*this);   // make a copy for result
               ++(*this);              // Now use the prefix version to do the work
               return result;          // return the copy (the old) value.
            }
    };