2013-03-28 72 views
-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; 
} 
+1

取決於「持續時間」的定義。它的持續時間由這些字段組成,只是返回創建的持續時間。 – Zeta

+4

你應該得到一些關於C++的入門書籍。 –

+0

我必須在函數內部創建一個新對象嗎?還是我傳遞對象? – FJam

回答

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,它可以是這樣的:

​​

而且這樣調用:

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; 
}