C++ 利用Clock类和Date类定义一个带日期的时钟类ClockWithDate,且对该对象能进行增加秒数的操作
#include iostream using namespace std; // 日期类年、月、日 class Date { private: int year, month, day; public: Date(int y 2026, int m 1, int d 1) : year(y), month(m), day(d) {} // 日期1简化不区分大小月只模拟进位 void nextDay() { day; if (day 30) { day 1; month; } if (month 12) { month 1; year; } } void showDate() { cout year - month - day ; } }; // 时钟类时、分、秒 class Clock { private: int hour, min, sec; public: Clock(int h 0, int m 0, int s 0) : hour(h), min(m), sec(s) {} // 增加1秒返回true代表满24点需要日期进一天 bool addSec() { sec; if (sec 60) { sec 0; min; } if (min 60) { min 0; hour; } if (hour 24) { hour 0; return true; } return false; } void showTime() { cout hour : min : sec; } }; // 带日期的时钟类组合Date和Clock class ClockWithDate { private: Date date; Clock clock; public: // 构造函数初始化日期时间 ClockWithDate(int y, int m, int d, int h, int mi, int s) : date(y, m, d), clock(h, mi, s) { } // 增加1秒自动处理日期进位 void addSecond() { bool needAddDay clock.addSec(); if (needAddDay) date.nextDay(); } // 打印完整日期时间 void show() { date.showDate(); clock.showTime(); cout endl; } }; int main() { cout 2504102043谭杰骏; ClockWithDate t(2026, 6, 23, 23, 59, 58); cout 初始时间; t.show(); t.addSecond(); cout 加1秒后; t.show(); t.addSecond(); cout 再加1秒后跨天; t.show(); return 0; }

相关新闻