实现平台:VS 2013,不同的平台,头文件可能会有所不同,在此处注意Windows下清屏为“cls”,睡眠为Sleep()等。
头文件部分
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
#include<time.h>
#include<iomanip>
#include<windows.h>
时钟类的实现部分
class Clock
{
public:
Clock()
{
time_t t = time(NULL);
//初始化数据来自当前系统时间
struct tm ti = *localtime(&t);
// struct tm * __CRTDECL localtime(const time_t * _Time)
_hour = ti.tm_hour;
_min = ti.tm_min;
_sec = ti.tm_sec;
}
void run()
{
while (1)
{
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 << endl;
}
void tick()
{
Sleep(1);
if (++_sec == 60)
{
_sec = 0;
_min += 1;
if (++_min==60)
{
_min = 0;
_hour += 1;
if (++_hour == 24)
{
_hour = 0;
}
}
}
}
private:
int _hour;
int _min;
int _sec;
};
主函数部分,实例化时钟类,调用时钟类函数
int main()
{
Clock c;
c.run();
}