简体   繁体   中英

Trying to overrun time in a constructor

I have a constructor in which I am trying to overrun time. So if the user enters 63 seconds, the 60 seconds get passed on to the minute because it is impossible to have 63 seconds in a minute. This is what I have. I need help with the commented section.

Time::Time(int hours, int minutes, int seconds, int millis) {

        /*int add_millis = millis;
        minutes -= add_millis*60000 ;
        millis += add_millis;*/

        int add_seconds = millis / 1000;
        millis -= add_seconds * 1000;
        seconds += add_seconds;

        int add_minutes = seconds / 60;
        seconds -= add_minutes * 60;
        minutes += add_minutes;

        int add_hours = minutes / 60;
        minutes -= add_hours * 60;
        hours += add_hours;

        hours %= 24;

Firstly, you need to decide if Time is a 'thing'. It doesn't seem to be in your example. What you want instead of an object is a function, which is a better representation of an 'action' that you perform on 'things'.

Your constructor only seems to operate on variables you pass to them by value (ie no member variables, no references), which brings us to the second point: any change you make to the parameters, will only be seen locally. You need to pass by reference or otherwise store them somewhere (ie member variables).

Thirdly: you want to cascade your changes from smaller to larger units of time, so you only have to wrap each of them once.

With this in mind, your functionality implemented as a function with parameters passed by reference:

#include <cassert>

void ValidateTime(int& hours, int& minutes, int& seconds, int& ms)
{
    assert(ms >= 0);
    assert(seconds >= 0);
    assert(minutes >= 0);
    assert(hours >= 0);

    int add_seconds = ms / 1000;
    ms %= 1000;

    seconds += add_seconds;
    int add_minutes = seconds / 60;
    seconds %= 60;

    minutes += add_minutes;
    int add_hours = minutes / 60;
    minutes %= 60;

    hours += add_hours;
    // TODO: exercise for the reader: roll your hours into days.
}

Usage example:

int main()
{
    int hours = 1;
    int minutes = 125;
    int seconds = 63;
    int ms = 54100;
    ValidateTime(hours, minutes, seconds, ms);

    std::cout << "hours: " << hours << ", minutes: " << minutes << ", seconds: " << seconds << ", ms: " << ms;
}

Prints hours: 3, minutes: 6, seconds: 57, ms: 100

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM