实现基本日期类型的加减操作
demo:通过给指定日期加减一个天数
计算两个日期之间相差的天数
通过数组给月份赋值
通过operator重载符号对内置类型符号重载
*注意operator赋值时候应该满足日期类的实际情况
month < 12 && February == 29 || 28
计算月份时候必须对闰年分开处理,因为闰年的Feburary是28天
加减天数时候需要考虑闰年的情况
*具体的代码实现
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
: _year(year)
, _month(month)
, _day(day)
{
if( !(year >= 0 &&
month > 0 && month < 13 &&
day > 0 && day <= _GetDaysOfMonth(year, month)))
{
_year = 1900;
_month = 1;
_day = 1;
}
}
Date operator+(int days)
{
if(days < 0)
return *this - (0 - days);
Date temp(*this);
temp._day += days;
int daysOfMonth;
while(temp._day > (daysOfMonth = _GetDaysOfMonth(temp._year, temp._month)))
{
temp._day -= daysOfMonth;
temp._month++;
if(temp._month > 12)
{
temp._year += 1;
temp._month = 1;
}
}
return temp;
}
Date operator-(int days)
{
if(days < 0)
return *this + (0 - days);
Date temp(*this);
temp._day -= days;
while(temp._day <= 0)
{
temp._month--;
if(0 == temp._month)
{
temp._year -= 1;
temp._month = 12;
}
temp._day += _GetDaysOfMonth(temp._year, temp._month);
}
return temp;
}
int operator-(const Date& d)
{
Date minDate(*this);
Date maxDate(d);
if(maxDate < minDate)
{
minDate = d;
maxDate = *this;
}
size_t count = 0;
while(minDate < maxDate)
{
count++;
++minDate;
}
return count;
}
bool IsLeap()
{
return _IsLeap(_year);
}
Date& operator++()
{
*this = *this + 1;
return *this;
}
Date operator++(int)
{
Date temp(*this);
++(*this);
return temp;
}
Date& operator--()
{
*this = *this - 1;
return *this;
}
Date operator--(int)
{
Date temp(*this);
--(*this);
return temp;
}
bool operator<(const Date& d)
{
if(_year < d._year ||
(_year == d._year && _month < d._month) ||
(_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)
{
return !(*this == d);
}
private:
int _GetDaysOfMonth(int year, int month)
{
int days[] = {0, 31,28,31,30,31,30,31,31,30,31,30,31};
if(2 == month && _IsLeap(year))
days[2] += 1;
return days[month];
}
bool _IsLeap(int year)
{
if((0 == year%4 && 0 != year % 100)||
(0 == year % 400))
{
return true;
}
return false;
}
friend ostream& operator<<(ostream& _cout, const Date& d)
{
_cout<<d._year<<"/"<<d._month<<"/"<<d._day;
return _cout;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2018, 6,24);
Date d2(2019, 1, 1);
cout<<d2 - d1<<endl;
cout<<d1-99<<endl;
cout<<d1-999<<endl;
cout<<d1 + (-99)<<endl;
return 0;
}