用面向对象思想实现时钟C++描述的实例代码:
# include# include # include # include //# include using namespace std;//初始化的数据来自系统,以后的逻辑运算及显示自实现class Clock{public: Clock() { time_t t = time(NULL); struct tm ti = *localtime(&t); hour = ti.tm_hour; min = ti.tm_min; sec = ti.tm_sec; } void run() { while (1) { system("cls"); show(); //完成显示 tick();//数据更新 } }private: void show() { //system("cls"); cout << setw(2) << setfill('0') << hour << ":"; cout << setw(2) << setfill('0') << min << ":"; cout << setw(2) << setfill('0') << sec << ":"; } void tick() { Sleep(1); if (++sec == 60) { sec = 0; min += 1; if (++min == 60) { min = 0; hour += 1; if (++hour == 24) { hour = 0; } } } } int hour = 0; int min = 0; int sec = 0;};int main(void){ Clock c; c.run(); cout << " Hello World " << endl; return 0;}