用面向對象思想實現時鐘C++描述

用面向對象思想實現時鐘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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章