-1

我有一个名为 Duration 的结构,我将如何更改此函数以使其返回 Duration 类型的对象?另一个问题是,如果我必须重载函数,我将如何让它接受持续时间对象?

void all(clock_t t, int &hours, int &minutes, int &seconds, int &ticks) {
    ticks = t % CLOCKS_PER_SEC;
    seconds = t / CLOCKS_PER_SEC;
    minutes = seconds / 60;
    seconds %= 60;
    hours = minutes / 60;
    minutes %= 60;
}
4

1 回答 1

2

假设您的Duration结构是这样的:

struct Duration {
   int hours, minutes, seconds, ticks;
};

现在您的all()方法可能如下所示:

Duration all(clock_t t) {
    Duration duration;
    duration.ticks = t % CLOCKS_PER_SEC;
    duration.seconds = t / CLOCKS_PER_SEC;
    duration.minutes = duration.seconds / 60;
    duration.seconds %= 60;
    duration.hours = duration.minutes / 60;
    duration.minutes %= 60;
    return duration;
}

并被称为:

clock_t t = ...;
Duration duration = all(t);

要回答您的另一个问题,如果您想重载all()以接受Durationfor 输出,它可能如下所示:

void all(clock_t t, Duration &duration) {
    duration.ticks = t % CLOCKS_PER_SEC;
    duration.seconds = t / CLOCKS_PER_SEC;
    duration.minutes = duration.seconds / 60;
    duration.seconds %= 60;
    duration.hours = duration.minutes / 60;
    duration.minutes %= 60;
}

并被称为:

clock_t t = ...;
Duration duration;
all(t, duration);

如果您重载,您可以使用另一个重载来实现一个重载以减少重复代码,如下所示:

Duration all(clock_t t) {
    Duration duration;
    duration.ticks = t % CLOCKS_PER_SEC;
    duration.seconds = t / CLOCKS_PER_SEC;
    duration.minutes = duration.seconds / 60;
    duration.seconds %= 60;
    duration.hours = duration.minutes / 60;
    duration.minutes %= 60;
    return duration;
}

void all(clock_t t, Duration &duration) {
    duration = all(t);
}

或这个:

void all(clock_t t, Duration &duration) {
    duration.ticks = t % CLOCKS_PER_SEC;
    duration.seconds = t / CLOCKS_PER_SEC;
    duration.minutes = duration.seconds / 60;
    duration.seconds %= 60;
    duration.hours = duration.minutes / 60;
    duration.minutes %= 60;
}

Duration all(clock_t t) {
    Duration duration;
    all(t, duration);
    return duration;
}
于 2013-03-28T21:51:54.300 回答