C++ 多重继承实现日期和时间类
C++ 多重继承实现日期和时间类
本示例演示了如何在 C++ 中使用多重继承定义日期类 Date、时间类 Time 以及带日期的时间类 TimeWithDate,实现对时间的设置和读取功能,并包含闰年判断。
#include <iostream>
using namespace std;
class Date {
private:
int year, month, day;
public:
Date(int y, int m, int d) {
year = y;
month = m;
day = d;
}
int getYear() { return year; }
int getMonth() { return month; }
int getDay() { return day; }
bool isLeapYear() {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
return true;
else
return false;
}
};
class Time {
private:
int hour, minute, second;
public:
Time(int h, int m, int s) {
hour = h;
minute = m;
second = s;
}
int getHour() { return hour; }
int getMinute() { return minute; }
int getSecond() { return second; }
};
class TimeWithDate : public Date, public Time {
public:
TimeWithDate(int y, int m, int d, int h, int mi, int s) : Date(y, m, d), Time(h, mi, s) {}
};
int main() {
int year, month, day, hour, minute, second;
cout << "Enter year, month, day, hour, minute, second: ";
cin >> year >> month >> day >> hour >> minute >> second;
TimeWithDate timeWithDate(year, month, day, hour, minute, second);
cout << "Date: " << timeWithDate.getYear() << "-" << timeWithDate.getMonth() << "-" << timeWithDate.getDay() << endl;
cout << "Time: " << timeWithDate.getHour() << ":" << timeWithDate.getMinute() << ":" << timeWithDate.getSecond() << endl;
if (timeWithDate.isLeapYear())
cout << "This is a leap year." << endl;
else
cout << "This is not a leap year." << endl;
return 0;
}
运行程序,输入日期和时间信息,即可输出设置的日期和时间,以及是否为闰年。
原文地址: https://www.cveoy.top/t/topic/n5sW 著作权归作者所有。请勿转载和采集!