#include <iostream>
#include <cstring>
using namespace std;
class Date {
public:
// 判断是否为闰年
bool isLeapYear(int year) const {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
// 获取任意月份的天数
int GetMonthDay(int year, int month) {
static int monthArray[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int day = monthArray[month];
// 判断是否是闰年闰月
if (month == 2 && isLeapYear(year)) {
day = 29;
}
return day;
}
Date(int year, int month, int day)
: _year(year)
, _month(month)
, _day(day)
{}
bool operator<(const Date& d) const {
if (this->_year < d._year) {
return true;
} else if (this->_year == d._year && this->_month < d._month) {
return true;
} else if (this->_year == d._year && this->_month == d._month &&
this->_day < d._day) {
return true;
}
return false;
}
bool operator!=(const Date& d) {
if (this->_year != d._year || this->_month != d._month ||
this->_day != d._day) return true;
else return false;
}
Date& operator+=(int day) {
_day += day;
while (_day > GetMonthDay(_year, _month)) {
// 如果日期不合法,就要往月进位
_day -= GetMonthDay(_year, _month);
++_month;
// 如果月不合法,就要往年进位
if (_month > 12) {
++_year;
_month = 1;
}
}
return *this;
}
int operator-(const Date& d) {
Date max = *this;
Date min = d;
if (*this < d) {
max = d;
min = *this;
}
int count = 1;
while (min != max) {
min += 1;
++count;
}
return count;
}
private:
int _year;
int _month;
int _day;
};
int main() {
int year, month, day;
scanf("%4d%2d%2d", &year, &month, &day);
Date d1(year, month, day);
scanf("%4d%2d%2d", &year, &month, &day);
Date d2(year, month, day);
cout << d1 - d2 << endl;
return 0;
}
如果你想看一个更完备的Date类,速通所有关于日期类的程序题,可以关注一下我新写的博客。学会Date类的编写,可以根据题目要求,自定义裁切Date类完成解答。 https://blog.csdn.net/mmlhbjk/article/details/141825524?spm=1001.2014.3001.5502

京公网安备 11010502036488号