设计符合下述要求的日期类(Date),使得下述代码可以正常运行。 拥有数据成员year、month和day,分别存储年、月、日; 构造函数接受年、月、日参数并初始化全部数据成员; 公有成员函数toText()返回一个string对象,该字符串为该日期对象的文字表达,比如“2022-5-20”; 公有成员函数nextDay()返回一个Date对象,表示该日期的后一天; 公有成员函数prevDay()返回一个Date对象,表示该日期的前一天。 裁判测试程序样例: #include <iostream> #include <string> #include <assert.h> using namespace std; //请在此处定义Date类 int main() { int year=2000,month=1,day=1; cin >> year >> month >> day; Date d(year,month,day); cout << "Date: " << d.toText() << ", Next Day: " << d.nextDay().toText() << ", Prev Day: " << d.prevDay().toText(); return 0; } 输入样例: 2000 3 1 说明:依次是年-月-日。 输出样例: Date: 2000-3-1, Next Day: 2000-3-2, Prev Day: 2000-2-29 提示:需要注意闰年,闰年2月有29天,平年28天。 闰年判定函数: bool isLeapYear(int year){ //四年一闰,百年不闰,四百年又闰 if (year%400==0) return true; else if (year%100==0) return false; else if (year%4==0) return true; else return false; }
时间: 2023-06-25 18:04:49 浏览: 152
```cpp
#include <iostream>
#include <string>
#include <assert.h>
using namespace std;
class Date {
private:
int year, month, day;
public:
Date(int y, int m, int d) {
year = y;
month = m;
day = d;
}
string toText() {
string s = to_string(year) + "-";
if (month < 10)
s += "0";
s += to_string(month) + "-";
if (day < 10)
s += "0";
s += to_string(day);
return s;
}
bool isLeapYear(int year) {
if (year % 400 == 0)
return true;
else if (year % 100 == 0)
return false;
else if (year % 4 == 0)
return true;
else
return false;
}
Date nextDay() {
int daysInMonth;
if (month == 2) {
if (isLeapYear(year))
daysInMonth = 29;
else
daysInMonth = 28;
}
else if (month == 4 || month == 6 || month == 9 || month == 11) {
daysInMonth = 30;
}
else {
daysInMonth = 31;
}
if (day == daysInMonth) {
if (month == 12) {
year++;
month = 1;
day = 1;
}
else {
month++;
day = 1;
}
}
else {
day++;
}
return Date(year, month, day);
}
Date prevDay() {
if (day == 1) {
if (month == 1) {
year--;
month = 12;
day = 31;
}
else {
month--;
if (month == 2) {
if (isLeapYear(year))
day = 29;
else
day = 28;
}
else if (month == 4 || month == 6 || month == 9 || month == 11) {
day = 30;
}
else {
day = 31;
}
}
}
else {
day--;
}
return Date(year, month, day);
}
};
int main() {
int year = 2000, month = 1, day = 1;
cin >> year >> month >> day;
Date d(year, month, day);
cout << "Date: " << d.toText() << ", Next Day: " << d.nextDay().toText() << ", Prev Day: " << d.prevDay().toText();
return 0;
}
```
阅读全文