实现跨天跨年的代码分享
#include
#include
using 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 AM
Clock(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 PM
ClockWithDate 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;
}
