实现跨天跨年的代码分享

发布时间:2026/6/24 1:38:54
实现跨天跨年的代码分享 #include#includeusing namespace std;// 日期基类class Date {protected:int year, month, day;// 获取当月合法最大天数兼容闰年int getMaxDay() const {int monthDays[13] { 0,31,28,31,30,31,30,31,31,30,31,30,31 };if (month 2 ((year % 4 0 year % 100 ! 0) || year % 400 0))return 29;return monthDays[month];}public:Date(int y 2026, int m 1, int d 1) : year(y), month(m), day(d) {}// 日期增加1天void addOneDay() {day;if (day getMaxDay()){day 1;month;if (month 12){month 1;year;}}}// 打印日期void showDate() const {printf(“%d-%02d-%02d”, year, month, day);}};// 时钟基类class Clock {protected:int hour, minute, second;string period;public:// 构造函数初始化时间默认00:00:00 AMClock(int h 0, int m 0, int s 0, string p “AM”): hour(h), minute(m), second(s), period§ {}// 单秒递增void addSecond() {second;if (second 60){second 0;minute;if (minute 60){minute 0;hour;if (hour 12){hour % 12;period (period “AM”) ? “PM” : “AM”;if (hour 0) hour 12;}}}}void showTime() const{printf(%02d:%02d:%02d %s , hour, minute, second, period.c_str());}};// 多重继承日期时钟一体类class ClockWithDate : public Date, public Clock {public:// 多父类构造初始化ClockWithDate(int y 2026, int mo 1, int d 1, int h 0, int mi 0, int s 0, string p “AM”): Date(y, mo, d), Clock(h, mi, s, p) {}// 批量加N秒自动处理跨天、跨年 void addManySeconds(int addNum) { for (int i 0; i addNum; i) { // 记录加秒前时刻 bool isMidnightCross (hour 11 minute 59 second 59); addSecond(); // 若刚好从11:59:59变为12:00:00说明跨一天 if (isMidnightCross hour 12 minute 0 second 0) { addOneDay(); } } } // 完整输出 日期时间 void showAllInfo() const { showTime(); showDate(); cout endl; }};int main(){// 初始化2026年12月31日 23:59:59 PMClockWithDate dt(2026, 12, 31, 11, 59, 59, “PM”);cout “初始日期时间” endl;dt.showAllInfo();int secInput;cout “请输入要增加的总秒数”;cin secInput;dt.addManySeconds(secInput);cout “\n增加 secInput 秒后” endl;dt.showAllInfo();return 0;}