简体   繁体   English

试图在构造函数中超时

[英]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.因此,如果用户输入 63 秒,则 60 秒将传递给分钟,因为一分钟内不可能有 63 秒。 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打印hours: 3, minutes: 6, seconds: 57, ms: 100

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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