0

I am trying to implement a time class which sets time, prints it and increases by one second. I want to make it by overloading the ++ operator, and it works fine but only when I define an argument in the parameter list. How can I make it work without defining any parameters, since I know that it increases the current time by one second and I don't need any arguments?

#include <iostream>

using namespace std;

class time
{
    int h,m,s;
public:
    time(int a, int b, int c);
    void printtime();
    time& operator++(int);
};

[...]

time& time::operator++(int x)
{
    s++;
if (s>59) {
    m++;
    s -= 60;
    if (m>59) {
        h++;
        m -= 60;
        if (h>23) {
            h = m = s = 0;
        }
    }
}
return *this;
}

int main()
{
try {
time now(22,58,59);
now.printtime();
now++;
now.printtime();
}
catch(const char* u) {
    cout << u << endl;
}

return 0;
}

Also, I will need to implement the postfix operator, which increases time, but only after printing the old time, so that

time now(2,23,59);
(now++).printtime();

will print 2:23:59, but after that the value of now will be 3,0,0. How can I implement both prefix and postfix ++ operators and make a difference when calling them in the main function?

Lois2B
  • 111
  • 1
  • 16

1 Answers1

3

The problem is there are two operators called ++. One is a pre-increment and one is a post-increment.

In order to distinguish them, the creators of C++ decided the post-increment version would take an "int" parameter. It isn't used, but it needs to be there, otherwise it is a pre-increment operator.

If you want to remove the parameter, you can use it like this:

++now;

Also, the post-increment version really needs to return a COPY of the structure, with the state as it was before it was incremented. That is the main difference between pre- and post- operators. It is much simpler to implement the pre operator, so if that's all you need, that's what you should use.

For completeness, here are the operators and how they should be written for a class T:

T& T::operator++();   [pre-increment]
T& T::operator--();   [pre-decrement]
T T::operator++(int); [post-increment]
T T::operator--(int); [post-decrement]

Note that the pre- versions return a reference to the object, whereas the post- version return a copy (not a reference). That copy should contain the value as it was prior to the increment/decrement.

Garr Godfrey
  • 8,257
  • 2
  • 25
  • 23
  • You could also have mentioned that the postfix version shouldn't return a reference, only the prefix version does. – papagaga Apr 16 '18 at 08:48
  • @papagaga Yep, I was editing that as your comment was added. – Garr Godfrey Apr 16 '18 at 08:49
  • Yes, I've figured it out already from your comment, but thank you. That's exactly how I implemented it, and it works fine. :) Many thanks! – Lois2B Apr 16 '18 at 09:05