最近在复习C++的时候发现日期类是一个非常有用的类,在现实中是非常实用的(虽然我不知道为什么这么实用的类,库里没有)以下是我自己实现的日期类的代码,因为大部分都是运算符的重载,所以理解起来应该并不难
#include <iostream>
#include <assert.h>
using namespace std;
class Date
{
friend ostream& operator<<(ostream& out,const Date& d);
friend istream& operator>>(istream& in, Date& d);
public:
Date (int year=1900,int month=1,int day=1)
{
_year=year;
_month=month;
_day=day;
if (month<1||month>12
||day<1||day>GetMonthDay(year,month))
{
assert (false);
}
}
Date(const Date& d)
{
_year=d._year;
_month=d._month;
_day=d._day;
}
Date& operator=(const Date& d)
{
if (this!=&d)
{
_year=d._year;
_month=d._month;
_day=d._day;
}
return *this ;
}
bool IsLeapYear(int year)
{
if ((year%4==0&&year%100!=0)||year%400==0)
{
return true;
}
return false;
}
int GetMonthDay(int year,int month)
{
assert (month > 0 && month < 13);
static int monthdays[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int day=monthdays[month];
if (month==2&&IsLeapYear(year))
day+=1;
return day;
}
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 !(*this <=d);
}
bool operator<=(const Date& d)
{
return *this<d||*this==d;
}
bool operator>=(const Date& d)
{
return !(*this <d);
}
bool operator==(const Date& d)
{
return _year==d._year&&_month==d._month&&_day==d._day;
}
bool operator!=(const Date& d)
{
return !(*this ==d);
}
Date operator+ (int day)
{
if (day<0)
{
return *this-(-day);
}
Date ret(*this);
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)
{
if (day<0)
{
return *this +(-day);
}
Date ret (*this );
ret._day-=day;
while (ret._day<=0)
{
ret._month--;
if (ret._month==0)
{
ret._year--;
ret._month=12;
}
ret._day+=GetMonthDay(ret._year,ret._month);
}
return ret;
}
Date& operator+=(int day)
{
*this =*this +day;
return *this;
}
Date& operator -=(int day)
{
*this =*this -day;
return *this ;
}
Date& operator++()
{
*this +=1;
return *this ;
}
Date operator++(int)
{
Date tmp(*this );
*this+=1;
return tmp;
}
int operator-(const Date& d)
{
int flag=1;
Date max=*this,min=d;
if (*this <d)
{
max=d;
min=*this;
flag=-1;
}
int days=0;
while (min<max)
{
++min;
++days;
}
return days*flag;
}
void Show ()
{
cout<<(*this)._year<<"-"<<_month<<"-"<<_day<<endl;
}
private:
int _year;
int _month;
int _day;
};
ostream& operator<<(ostream& out,const Date& d)
{
out<<d._year<<"-"<<d._month<<"-"<<d._day<<endl;
return out;
}
istream& operator>>(istream& in, Date& d)
{
in>>d._year;
in>>d._month;
in>>d._day;
return in;
}
void TestDate()
{
Date d1(2018,3,15);
d1+=100;
d1.Show();
}
int main ()
{
TestDate();
return 0;
}