题解 | #打印日期#
打印日期
https://www.nowcoder.com/practice/b1f7a77416194fd3abd63737cdfcf82b
# define _CRT_SECURE_NO_WARNINGS 1 #include <iostream> #include <stdbool.h> using namespace std; class Date { friend ostream& operator<<(ostream& out, const Date& d); public: Date(int year = 1, int month = 1, int day = 0) :_year(year) , _month(month) , _day(day) {} int GetMonthDay(int year, int month); bool operator<(Date& d) { if (_year < d._year) { return true; } else if (_year == d._year) { if (_month < d._month) { return true; } else if (_month == d._month) { if (_day < d._day) { return true; } } } return false; } bool operator==(Date& d) { return _year == d._year && _month == d._month && _day == d._day; } Date operator+(int day) { Date temp = *this; temp += day; return temp; } Date& operator++() { *this += 1; return *this; } //d1+=50 Date& operator+=(int day) { _day += day; while (_day > GetMonthDay(_year, _month)) { //cout << _year <<' '<< _month << endl; //cout << GetMonthDay(_year, _month) << endl; _day -= GetMonthDay(_year, _month); ++_month; if (13 == _month) { _month = 1; ++_year; } } return *this; } private: int _year ; int _month; int _day ; }; int Date::GetMonthDay(int year, int month) { static int Monthday[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 }; if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))) { return 29; } else { return Monthday[month]; } } ostream& operator<<(ostream& out, const Date& d) { if (d._month < 10 && d._day < 10) { out << d._year << "-0" << d._month << "-0" << d._day; } else if(d._month < 10 && d._day >= 10) { out << d._year << "-0" << d._month << "-" << d._day; } else if (d._month >= 10 && d._day < 10) { out << d._year << "-" << d._month << "-0" << d._day; } else { out << d._year << "-" << d._month << "-" << d._day; } return out; } int main() { int year = 2000, month = 1, day = 0; int n = 0; while (cin >> year >> n) { Date d1(year, month, day); Date d2 = d1 + n; cout << d2 << endl; } return 0; }