class Date
{
public:
int GetMonthDay(int year,int month)
{
int MonthDays[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;
}
return MonthDays[month];
}
Date(int year = 0, int month = 1,int day = 1)
{
if (year >= 0
&& month >= 1 && month <= 12
&& day >= 1 && day <=GetMonthDay(year,month))
{
_year = year;
_month = month;
_day = day;
}
else
{
cout << "非法日期" << endl;
}
}
Date(const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
bool operator<(const Date& d)
{
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;
return false;
}
bool operator==(const Date& d)
{
return _year == d._year && _month == d._month && _day == d._day;
}
bool operator<=(const Date& d)//bool operator<=(Date* this, const Date& d)
{
/*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;
return false;*/
//或者 *this就是d1,d就是d2
return *this < d || *this == d;
}
bool operator>(const Date& d)
{
return !(*this <= d);
}
bool operator>=(const Date& d)
{
return !(*this < d);
}
bool operator!=(const Date& d)
{
return !(*this == d);
}
Date& operator=(const Date& d)
{
if (this != &d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
return *this;
}
Date operator+(int day)
{
Date ret(*this);//d1拷贝构造 ret
ret._day += day;
while (ret._day > GetMonthDay(ret._year, ret._month))
{
ret._day -= GetMonthDay(ret._year, ret._month);
ret._month++;
if (ret._month == 13)
{
ret._year++;
ret._month = 1;
}
}
return ret;
}
Date& operator-=(int day)
{
_day -= day;
while (_day <= 0)
{
_month--;
if (_month == 0)
{
_year--;
_month = 12;
}
_day += GetMonthDay(_year, _month);
}
return *this;
}
Date operator-(int day)
{
Date ret = *this;
ret._day -= day;
ret._month--;
while(ret._day <= 0)
{
ret._month--;
if (ret._month == 0)
{
ret._year--;
ret._month = 12;
}
ret._day += GetMonthDay(ret._year, ret._month);
}
return ret;
}
void Print()
{
cout << _year << "-" << _month << "-" << _day<<endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2022, 2, 3);
d1.Print();
Date d2(2020, 2, 29);
d2.Print();
cout << (d1 < d2) << endl;
cout << (d1 > d2) << endl;
cout << (d1 == d2) << endl;
cout << (d1 != d2) << endl;
cout << (d1 <= d2) << endl;
cout << (d1 >= d2) << endl;
Date d3(2021, 1, 1);
d3.Print();
Date d4 = d3 + 400;
d4.Print();
Date d5 = d4 -= 400;
d5.Print();
//Date d1(2023, 11, 22);
//d1.Print();
//Date d2(d1);
//d2.Print();
//Date d3;
//d3 = d1;
//d3.Print();
return 0;
}