用面向对象思想实现时钟C++描述的实例代码:
# include <iostream> # include <time.h> # include <iomanip> # include <windows.h> //# include <unistd.h> 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; }
本文出自 “享受科技带来的快乐” 博客,请务必保留此出处http://liam2199.blog.51cto.com/2879872/1972448
原文地址:http://liam2199.blog.51cto.com/2879872/1972448