細化的某些階段:
第1階段:修復您的代碼。
struct tme {
char * intime; // You had a type mismatch
} e;
int main() { // Don't use void main()
char timeStr [9];
_strtime(timeStr);
e.intime=timeStr;
printf("The current time is %s \n", timeStr);
}
這裏有一個問題:你的struct tme
是依靠外部世界爲它做的一切,並因此正確地做。如果我們想重用主要的timeStr
會怎麼樣?如果在除main
之外的其他功能中使用此結構,並將e.intime
設置爲超出範圍的變量,該怎麼辦?
細化:struct tme
應該擁有時間緩衝區。
struct tme {
char intime[9]; // Put the buffer here, not in main.
} e;
int main() {
_strtime(e.intime);
printf("The current time is %s \n", e.intime);
}
這裏我們還是有問題。任何人都可以修改該緩衝區,而且該結構只是一個無源插座。
細化:隱藏數據並使對象處於活動狀態。
struct tme {
const char * set_time() { _strtime (intime); return intime; }
const char * get_time() const { return intime; }
private:
char intime[9];
};
int main() {
printf("The current time is %s \n", e.set_time());
}
請注意'_strtime'是一個Windows函數,它使您的代碼片段不符合標準。請考慮使用'const time_t current = time(NULL); strftime(timeStr,9,「%H:%M:%S」,localtime(&current));',即使它看起來像一小撮,因爲它不會不必要地依賴於(不推薦使用的)僅限Windows的函數。 – DevSolar