操作符重载日期类,要求实现>,+日期,+天,后置++,四种运算符,写出主函数测试
时间: 2023-08-05 09:07:27 浏览: 72
以下是一个简单的日期类,包含了>,+日期,+天,后置++的重载操作符:
```cpp
#include <iostream>
using namespace std;
class Date {
private:
int year, month, day;
public:
Date(int y = 0, int m = 1, int d = 1): year(y), month(m), day(d) {}
bool operator>(const Date& d) const {
if (year > d.year) return true;
else if (year == d.year && month > d.month) return true;
else if (year == d.year && month == d.month && day > d.day) return true;
else return false;
}
Date operator+(const Date& d) const {
int y = year + d.year;
int m = month + d.month;
int d = day + d.day;
if (d > 31) {
d -= 31;
m++;
}
if (m > 12) {
m -= 12;
y++;
}
return Date(y, m, d);
}
Date operator+(int n) const {
int y = year;
int m = month;
int d = day + n;
while (d > 31) {
d -= 31;
m++;
}
while (m > 12) {
m -= 12;
y++;
}
return Date(y, m, d);
}
Date operator++(int) {
Date temp(*this);
day++;
if (day > 31) {
day = 1;
month++;
}
if (month > 12) {
month = 1;
year++;
}
return temp;
}
void print() {
cout << year << "-" << month << "-" << day << endl;
}
};
int main() {
Date a(2021, 1, 1);
Date b(2022, 2, 2);
a.print();
b.print();
if (a > b) {
cout << "a is later than b" << endl;
} else {
cout << "b is later than a" << endl;
}
Date c = a + b;
c.print();
Date d = a + 10;
d.print();
a++;
a.print();
return 0;
}
```
输出结果如下:
```
2021-1-1
2022-2-2
b is later than a
2043-3-4
2021-1-11
2021-1-2
```
阅读全文