用C++写一个时钟怎么写
1个回答
展开全部
#define _CRT_SECURE_NO_WARNINGS
#include <cassert>
#include <iostream>
#include <iomanip>
#include <ctime>
class Date;
class Time {
public:
bool OVFlag;
Time(unsigned short const h_, unsigned short const m_, unsigned short const s_) :
OVFlag(false), h(h_), m(m_), s(s_) {
if (h_ >= 24 || m_ >= 60 || s_ >= 60) throw;// 检查时间是否合理
}
void tick(Date &d);
private:
unsigned short h, m, s;// 时分秒
template<typename Char, typename Traits>
friend std::basic_ostream<Char, Traits>& operator<<(std::basic_ostream<Char, Traits>& ostr, Time const &t) {
using std::setw;
using std::setfill;
return ostr
<< setw(2) << setfill('0') << t.h << ":"
<< setw(2) << setfill('0') << t.m << ":"
<< setw(2) << setfill('0') << t.s;
}
};
class Date {
public:
Date(unsigned short const y_, unsigned short const m_, unsigned short const d_) :
y(y_), m(m_), d(d_) {
if (1 > m_ || m_ > 12 || 1 > d_ || d_ > days(y_, m_)) throw;// 检查日期是否合理
}
void pass(Time &t);
private:
unsigned short y, m, d;// 年月日
static bool leap(unsigned short y);
static unsigned short days(unsigned short y, unsigned short m);
template<typename Char, typename Traits>
friend std::basic_ostream<Char, Traits>& operator<<(std::basic_ostream<Char, Traits>& ostr, Date const &d) {
using std::setw;
return ostr << d.y << "/" << d.m << "/" << d.d;
}
};
void Time::tick(Date &d) {
assert(OVFlag == false && h < 24 && m < 60 && s < 60);
if (++s == 60) {
// 过了一分钟
s = 0;
if (++m == 60) {
// 过了一小时
m = 0;
if (++h == 24) {
// 过了一天
h = 0;
OVFlag = true;
d.pass(*this);
}
}
}
}
bool Date::leap(unsigned short y) {
return (y % 4 == 0) || ((y % 100 != 0) && (y % 400 == 0));
}
unsigned short Date::days(unsigned short y, unsigned short m) {
switch (m) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
return 31;
case 4: case 6: case 9: case 11:
return 30;
case 2:
return leap(y) + 28;
default:
throw;// 不在正确的范围
}
}
void Date::pass(Time &t) {
assert(t.OVFlag == true);
t.OVFlag = false;
if (d++ == days(y, m)) {// 过了一个月
d = 1;
if (m++ == 12) {// 过了一年
m = 1;
++y;
}
}
}
int main() {
// 获取当前时间
time_t current_time;
time(¤t_time);
tm *local_time = localtime(¤t_time);
// 设置初始时间
Date d(1900 + local_time->tm_year, 1 + local_time->tm_mon, local_time->tm_mday);
Time t(local_time->tm_hour, local_time->tm_min, local_time->tm_sec);
// 开始模拟
clock_t last_clock = clock(), duration = 0;
while (true) {
clock_t const current_clock = clock();
duration += current_clock - last_clock;// 时间间隔
last_clock = current_clock;// 记下上次的时间
for (int i = 0; i != duration / CLOCKS_PER_SEC; ++i) {// 每经过1秒,调用1次tick
t.tick(d);
std::cout << d << " " << t << "\n";
}
duration %= CLOCKS_PER_SEC;
}
return 0;
}
使用公共属性OVFlag的弊端:打破封装,将实现细节暴露给外面,容易出错,不利于定位错误,调试和维护。
好处:访问起来很方便。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询