C++ 时钟类设计与实现
#include
class Clock { private: int hour; //小时 int minute; //分钟 int second; //秒 public: Clock() { //构造函数,初始化为0点0分0秒 hour = 0; minute = 0; second = 0; }
Clock(int h, int m, int s) { //构造函数,初始化为指定时间
hour = h;
minute = m;
second = s;
}
void setHour(int h) { //设置小时
hour = h;
}
void setMinute(int m) { //设置分钟
minute = m;
}
void setSecond(int s) { //设置秒
second = s;
}
void showTime() { //显示时间
cout << hour << ":" << minute << ":" << second << endl;
}
void getCurrentTime() { //获取当前时间
time_t t = time(NULL); //获取当前时间
tm* local = localtime(&t); //转换为本地时间
hour = local->tm_hour;
minute = local->tm_min;
second = local->tm_sec;
}
};
int main() { Clock c1; //默认时钟 c1.showTime();
Clock c2(8, 30, 0); //指定时钟
c2.showTime();
c2.setHour(9); //动态设置时间
c2.setMinute(20);
c2.setSecond(30);
c2.showTime();
Clock c3;
c3.getCurrentTime(); //获取当前时间
c3.showTime();
return 0;
原文地址: https://www.cveoy.top/t/topic/l4tK 著作权归作者所有。请勿转载和采集!