C++ 继承实现带日期的时间类 TimeWithDate
C++ 继承实现带日期的时间类 TimeWithDate
本示例展示了如何利用已给的 Time 类和 Date 类,通过继承这两个类,定义一个带日期的时间类 TimeWithDate。
类定义:
class Time {
int hour;
int minute;
int second;
public:
Time(int h = 0, int m = 0, int s = 0) : hour(h), minute(m), second(s) {}
void setTime(int h, int m, int s) { hour = h; minute = m; second = s; }
void showTime() { cout << hour << ':' << minute << ':' << second << endl; }
};
class Date {
int year;
int month;
int day;
public:
Date(int y = 0, int m = 0, int d = 0) : year(y), month(m), day(d) {}
void setDate(int y, int m, int d) { year = y; month = m; day = d; }
void showDate() { cout << year << '.' << month << '.' << day << endl; }
};
class TimeWithDate : public Time, public Date {
public:
TimeWithDate(int y = 0, int m = 0, int d = 0, int h = 0, int min = 0, int s = 0) : Date(y, m, d), Time(h, min, s) {}
void setTimeWithDate(int y, int m, int d, int h, int min, int s) { Date::setDate(y, m, d); Time::setTime(h, min, s); }
void showTimeWithDate() { Date::showDate(); Time::showTime(); }
};
主函数:
int main() {
TimeWithDate t1(2020, 10, 1, 12, 30, 0);
t1.showTimeWithDate();
t1.setTimeWithDate(2020, 10, 2, 10, 0, 0);
t1.showTimeWithDate();
return 0;
}
运行结果:
2020.10.1
12:30:0
2020.10.2
10:0:0
代码解析:
- 类 TimeWithDate 继承了 Time 和 Date 类,它拥有了这两个类的所有成员变量和成员函数。
- TimeWithDate 类的构造函数同时初始化了 Time 类和 Date 类的成员变量。
- setTimeWithDate() 函数分别调用了 Time 类和 Date 类的 setTime() 和 setDate() 函数来设置时间和日期。
- showTimeWithDate() 函数分别调用了 Time 类和 Date 类的 showTime() 和 showDate() 函数来输出时间和日期。
本示例演示了 C++ 中如何利用继承来创建新的类,并继承父类的成员变量和成员函数。通过合理地使用继承,可以使代码更简洁、易于维护。
原文地址: https://www.cveoy.top/t/topic/oOWE 著作权归作者所有。请勿转载和采集!