Overloading Operators using Time Object

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:
1
2
3
4
5
6
7
8
9
10
11
12
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

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]
your code goes here
maintains indentation
adds syntax highlighting
improves posture
[/code]
Last edited on
Topic archived. No new replies allowed.