我有一个名为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;
}
答案 0 :(得分: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()
以接受Duration
输出,则它可能如下所示:
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;
}