I have a task to implement the overloading of the operators: -- (pre and postfix), -, -=, <, <=, >, >=, == and !=. I have managed to do most of these, but I am having trouble with the -= operator. The Time object has member variables of hour, min and sec. Operator-= should subtract n number of seconds from the Time object.
For example:
where n = 30
[hh][mm][ss]
[00][02][10]
-[00][00][30]
=[00][01][40]

Here is my code at the moment:
 ``123456789101112`` ``````Time& Time::operator-=(unsigned int n) { sec -= n; if (sec < 0) { min -= 1; sec = 60 - (n - sec); if (min < 0) { hour = (hour - min/60) % 24; min %= 60; } } return *this; }``````

This is currently giving me negative values for the seconds, I would appreciate some advice as to where I'm going wrong here, thanks.
Last edited on
You can't assume that if n > sec (i.e., sec -= n goes negative) that you will only need to subtract 1 from the minute. What if you're subtracting 1000 seconds? Or 10000 seconds? There's 86400 seconds in a day.

It's probably best to do such calculations by converting your hour, min, sec form to number of seconds since midnight, subtract n from that, and then convert back. In fact, it would probably be best to store the time as the number of seconds since midnight in the first place. But maybe you don't want to do that.

And I don't agree with limiting n to an unsigned value. I think you should be able to subtract a negative value.

 ``123456789101112131415161718192021222324`` ``````#include void minus(int n, int& hour, int& min, int& sec) { const int HoursPerDay = 24; const int MinsPerHour = 60; const int SecsPerMin = 60; const int SecsPerHour = MinsPerHour * SecsPerMin; const int SecsPerDay = HoursPerDay * SecsPerHour; int x = sec + min * SecsPerMin + hour * SecsPerHour - n; x %= SecsPerDay; if (x < 0) x += SecsPerDay; hour = x / SecsPerHour; min = x % SecsPerHour / MinsPerHour; sec = x % SecsPerMin; } int main() { int hour = 14, min = 37, sec = 12, n = 317; minus(n, hour, min, sec); std::cout << hour <<':'<< min <<':'<< sec <<'\n'; }``````

(Hopefully someone will let me know if I'm using the modulus operator non-portably. I'm always a little worried using it with negative values.)

BTW, my code looks better than yours because I used code tags:

[code]