比方說你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
,它可以是這樣的:
而且這樣調用:
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;
}
取決於「持續時間」的定義。它的持續時間由這些字段組成,只是返回創建的持續時間。 – Zeta
你應該得到一些關於C++的入門書籍。 –
我必須在函數內部創建一個新對象嗎?還是我傳遞對象? – FJam