问题描述】
设计符合下述要求的日期类(Date),使得下述代码可以正常运行。
-
拥有数据成员year、month和day,分别存储年、月、日;
-
构造函数接受年、月、日参数并初始化全部数据成员;
-
公有成员函数toText()返回一个string对象,该字符串为该日期对象的文字表达,比如“2022-5-20”;
-
重载运算符++,返回一个Date对象,表示该日期的后一天;
-
重载运算符>,比较两个Date对象,表示两个日期的先后关系。
【提示】
可以使用to_string()函数将整型变量转成string
string s;
s=to_string(102);
【样例输入】
2023 12 31
2024 1 5
【样例输出】
Date1 is 2023-12-31
Date2 is 2024-1-5
Date1 is not bigger!
Next day of Date1 is 2024-1-1
#include <iostream>
#include <string>
using namespace std;
// 用于处理月份天数和闰年的辅助函数
bool isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
int daysInMonth(int year, int month) {
int daysPerMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month == 2 && isLeapYear(year)) {
return 29;
}
return daysPerMonth[month];
}
class Date {
private:
int year;
int month;
int day;
public:
// 构造函数
Date(int y, int m, int d) : year(y), month(m), day(d) {
// 这里可以添加对日期的有效性检查
}
// toText 函数
string toText() const {
return to_string(year) + '-' +
(month < 10 ? "0" : "") + to_string(month) + '-' +
(day < 10 ? "0" : "") + to_string(day);
}
// 重载++运算符
Date& operator++() {
day++;
if (day > daysInMonth(year, month)) {
day = 1;
month++;
if (month > 12) {
month = 1;
year++;
}
}
return *this;
}
// 重载>运算符
bool operator>(const Date& other) const {
if (year > other.year) return true;
if (year < other.year) return false;
if (month > other.month) return true;
if (month < other.month) return false;
return day > other.day;
}
};
int main() {
int year1, month1, day1;
cin >> year1 >> month1 >> day1;
Date d1(year1, month1, day1);
int year2, month2, day2;
cin >> year2 >> month2 >> day2;
Date d2(year2, month2, day2);
cout << "Date1 is " << d1.toText() << endl;
cout << "Date2 is " << d2.toText() << endl;
if (d1 > d2)
cout << "Date1 is bigger!" << endl;
else
cout << "Date1 is not bigger!" << endl;
cout << "Next day of Date1 is " << (++d1).toText() << endl;
return 0;
}