功能实现:在一个日期上+N天、-N天,重载前置++/--和后置++/--以及两个日期之间的差距,还有就是比较两个日期之间的大小。
#include<iostream>
using namespace std;
class Date
{
friend ostream & operator<<(ostream& os, Date& d)//输出运算符重载
{
os << d._year << "-" << d._month << "-" << d._day;
return os;
}
public:
Date( int year = 1900, int month = 1, int day = 1)//构造函数
:_year( year)
,_month( month)
,_day( day)
{
if (Invalid())
{
_year = 1900;
_month = 1;
_day = 1;
}
}
//检查日期是否不合法
bool Invalid()
{
if (_year < 1900 || _month<1 || _month>12 || _day<0 || _day>GetMonthDay(_month))
{
return true ;
}
return false ;
}
//获取每月的天数
int GetMonthDay(int month)
{
int date[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (IsLeap())
{
date[2]+= 1;
}
return date[month ];
}
//判断是否是闰年
bool IsLeap()
{
if ((_year % 400 == 0) || ((_year % 4 == 0) && (_year % 100 != 0)))
{
return true ;
}
else
return false ;
}
Date( Date & d )//拷贝构造
{
_year = d._year;
_month = d._month;
_day = d._day;
}
//修正日期
void ToCorrect(Date & temp)
{
while (temp ._day <= 0)
{
if (temp ._month == 1)
{
temp._month = 12;
temp._year--;
}
else
{
temp._month -= 1;
}
temp._day += GetMonthDay(temp ._month);
}
while (temp ._day > GetMonthDay(temp._month))
{
temp._day -= GetMonthDay(temp ._month);
if (temp ._month == 12)
{
temp._month = 1;
temp._year++;
}
else
{
temp._month++;
}
}
}
//日期加天数
Date operator+(int day)
{
Date temp(*this );
temp._day += day;
ToCorrect(temp);
return temp;
}
//日期减天数
Date operator-(int day)
{
Date temp(*this );
temp._day -= day;
ToCorrect(temp);
return temp;
}
//日期减日期
int operator-(Date & d)
{
Date min(*this );
Date max(d );
if (min>max)
{
max = * this;
min = d;
}
int count=0;
while (min != max)
{
min++;
count++;
}
return count;
}
bool operator>(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==(Date & d)
{
return _year == d ._year&&_month == d._month&&_day == d._day;
}
bool operator<(Date &d)
{
return !(*this >d && * this == d );
}
bool operator!=(Date & d)
{
return !(*this == d);
}
Date& operator=(Date & d)//赋值
{
_year = d._year;
_month = d._month;
_day = d._day;
return *this ;
}
Date& operator+(Date & d)//加法
{
_year += d._day;
_month += d._month;
_day += d._day;
return *this ;
}
Date& operator++()//前置++
{
* this=*this +1;
return *this ;
}
Date operator++(int )//后置++
{
Date temp(*this );
* this = *this + 1;
return temp;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2016, 4, 6);
cout << d1 - 100 << endl;
Date d2(1994, 3, 24);
cout << d1 - d2 << endl;
getchar();
return 0;
}