代码实现
#include<iostream>
#include<stdlib.h>
using namespace std;
class Date
{
public:
Date(int year = 1990, int month = 10, int day = 10)
{
if (!((year > 0) && (0 < month <= 12) && (0 < day < 31)))
{
_year = 1990;
_month = 10;
_day = 10;
}
else
{
_year = year;
_month = month;
_day = day;
}
}
friend ostream&operator<<(ostream&_cout, const Date& d);
bool Date::operator==(const Date& d)
{
return _year == d._year && _month == d._month && _day == d._day;
}
bool Date::operator!=(const Date& d)
{
return !(*this == d);
}
int Date::operator-(const Date& d)
{
int day = 0;
Date small(d);
Date big(*this);
if (*this < d)
{
small = *this;
big = d;
}
else
{
small = d;
big = *this;
}
while (small != big)
{
small++;
day++;
}
return day;
}
bool Date::operator<(const 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;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
Date operator+(int days)
{
if (days < 0)
{
days = 0 - days;
}
_day = _day + days;
while (_day>(Getmonthdays(_year, _month)))
{
_day = _day - Getmonthdays(_year, _month);
_month++;
if (_month>11)
{
_month = 1;
_year++;
}
}
return *this;
}
Date operator-(int days)
{
if (days<0)
{
days = 0 - days;
}
days = (_day)-days;
while (days <= 0 && days<(Getmonthdays(_year, _month)))
{
days = days + Getmonthdays(_year, _month);
_month--;
if (_month <= 1)
{
_month = 12;
_year--;
}
}
_day = days;
return *this;
}
Date operator++()//前置加加
{
_day = _day++;
if (_day>Getmonthdays(_year, _month))
{
_day = _day - Getmonthdays(_year, _month);
_month++;
if (_month == 12)
{
_year++;
}
}
return *this;
}
Date operator++(int)//后置加加
{
Date temp = *this;
++(*this);
return temp;
}
bool IsLeapyear(int year)
{
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
{
return true;
}
return false;
}
~Date()
{
}
private:
int& Getmonthdays(int year, int month)
{
int temp;
int arr[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (IsLeapyear(year) && month == 2)
{
temp = arr[month] + 1;
}
temp = arr[month];
return temp;
}
private:
int _year;
int _month;
int _day;
};
ostream&operator<<(ostream&_cout, const Date& d)
{
_cout << d._year << "-" << d._month << "-" << d._day << endl;
return _cout;
}
void FunTest()
{
Date d1(2017, 1, 1);
Date d2(2017, 2, 1);
cout << d1 + 20 << endl;
cout << d1 - 20 << endl;
cout << ++d1 << endl;
cout << d1++ << endl;
cout << d1 - d2 << endl;
}
int main()
{
FunTest();
system("pause");
return 0;
}
结果实现: