#include <iostream> using namespace std; class Date { private: friend std::istream& operator>>(std::istream& _cin, Date& d); // 判断是否为闰年 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; } public: // 构造函数 Date(int year, int month = 1, int day = 1) { _year = year; _month = month; _day = day; } bool operator!=(const Date& d) const { if (this->_year == d._year && this->_month == d._month && this->_day == d._day) { return false; } return true; } Date& operator+=(int day) { // Date& operator+=(Date* this, 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; int flag = 1; int count = 0; while (min != max) { min += 1; count++; } return count * flag; } private: int _year; int _month; int _day; }; istream& operator>>(istream& _cin, Date& d) { _cin >> d._year >> d._month >> d._day; return _cin; } int main() { int year, month, day; while (cin >> year >> month >> day) { Date d1(year, month, day); Date d2(year, 1, 0); cout << d1 - d2; } return 0; }
如果你想看一个更完备的Date类,速通所有关于日期类的程序题,可以关注一下我新写的博客。学会Date类的编写,可以根据题目要求,自定义裁切Date类完成解答。 https://blog.csdn.net/mmlhbjk/article/details/141825524?spm=1001.2014.3001.5502