C++ 继承实现带日期的时间类 TimeWithDate
C++ 继承实现带日期的时间类 TimeWithDate
本文将使用 C++ 继承机制,利用已有的 Time 和 Date 类,定义一个包含日期和时间的 TimeWithDate 类。代码示例展示了类的定义和使用方法,并给出了运行结果。
类定义
#include <iostream>
using namespace std;
class Time {
public:
Time(int h = 0, int m = 0, int s = 0) {
hour = h;
minute = m;
second = s;
}
void display() {
cout << hour << ':' << minute << ':' << second << endl;
}
protected:
int hour, minute, second;
};
class Date {
public:
Date(int y = 0, int m = 0, int d = 0) {
year = y;
month = m;
day = d;
}
void display() {
cout << year << '-' << month << '-' << day << endl;
}
protected:
int year, month, day;
};
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) : Time(h, min, s), Date(y, m, d) {}
void display() {
cout << year << '-' << month << '-' << day << ' ';
cout << hour << ':' << minute << ':' << second << endl;
}
};
int main() {
int year, month, day, hour, minute, second;
cin >> year >> month >> day >> hour >> minute >> second;
TimeWithDate t1(year, month, day, hour, minute, second);
t1.display();
return 0;
}
代码说明
- 使用
public继承Time和Date类,使得TimeWithDate类拥有Time和Date类的所有成员变量和方法。 - 在
TimeWithDate类的构造函数中,使用初始化列表分别初始化了Time和Date类的成员变量。 - 重写了
display方法,以显示日期和时间。
运行结果
输入示例:
2023 12 25 10 30 45
输出结果:
2023-12-25 10:30:45
总结
通过继承,我们可以方便地扩展现有类,创建新的类,并复用已有类的功能。在本文中,我们利用继承机制,成功地定义了一个包含日期和时间的 TimeWithDate 类。
原文地址: https://www.cveoy.top/t/topic/oOWd 著作权归作者所有。请勿转载和采集!