设计并实现一个日期类Date,要求: (1)可以建立具有指定日期(年、月、日)的Date对象,默认日期是2009.1.1。 (3)可以设置年、月、日。 (4)可以用运算符<对两个日期进行比较 (5)可以用运算符++,完成天数的加减一天或若干天的操作
时间: 2024-01-23 22:03:09 浏览: 66
好的,我可以为您实现一个日期类Date。以下是代码实现:
```cpp
#include <iostream>
using namespace std;
class Date {
private:
int year;
int month;
int day;
public:
Date(int y = 2009, int m = 1, int d = 1) {
year = y;
month = m;
day = d;
}
void setDate(int y, int m, int d) {
year = y;
month = m;
day = d;
}
bool operator <(const Date& other) const {
if (year != other.year) {
return year < other.year;
} else if (month != other.month) {
return month < other.month;
} else {
return day < other.day;
}
}
Date operator ++(int) {
Date temp = *this;
day++;
if (day > getDaysInMonth()) {
day = 1;
month++;
}
if (month > 12) {
month = 1;
year++;
}
return temp;
}
int getDaysInMonth() const {
int daysInMonth;
switch (month) {
case 2:
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
daysInMonth = 29;
} else {
daysInMonth = 28;
}
break;
case 4:
case 6:
case 9:
case 11:
daysInMonth = 30;
break;
default:
daysInMonth = 31;
break;
}
return daysInMonth;
}
friend ostream& operator <<(ostream& os, const Date& date) {
os << date.year << "." << date.month << "." << date.day;
return os;
}
};
int main() {
Date d1(2020, 7, 1);
Date d2(2020, 8, 1);
cout << "d1: " << d1 << endl;
cout << "d2: " << d2 << endl;
if (d1 < d2) {
cout << "d1 < d2" << endl;
} else {
cout << "d1 >= d2" << endl;
}
d1++;
cout << "d1: " << d1 << endl;
return 0;
}
```
这个日期类实现了设置日期、比较日期、加减日期等基本操作。您可以根据需要进行扩展。
阅读全文