#include<iostream>
#include<assert.h>
using namespace std;
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
:_year(year) //初始化列表
,_month(month)
,_day(day)
{
assert(!IsInvalid());
}
Date& operator=(const Date& d)
{
if(this!=&d)
{
_year=d._year;
_day=d._day;
_month=d._month;
}
return *this;
}
bool IsInvalid()
{
if(!(_year>0&&_month>0&&_month<13&&_day>0&&_day<=GetMonthDay(_year,_month)))
{
return true;
}
return false;
}
bool isLeapYear(int year)
{
if((year%4==0&&year%100!=0)||(year%400==0))
{
return true;
}
return false;
}
int GetMonthDay(int year, int month)
{
int Month[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
if(month!=2)
{
return Month[month];
}
else
{
if(isLeapYear(year))
{
return 29;
}
else
{
return 28;
}
}
}
void Show()
{
cout<<_year<<"-"<<_month<<"-"<<_day<<endl;
}
bool operator==(const Date& d)
{
return _year==d._year
&&_month==d._month
&&_day==d._day;
}
bool operator!=(const Date& d)
{
return !(_year==d._year
&&_month==d._month
&&_day==d._day);
}
bool operator>=(const Date& d)
{
return (*this==d||*this>d);
}
bool operator<=(const Date& d)
{
return (*this==d||*this<d);
}
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;
}
// d1 < d2
bool operator<(const Date& d)
{
return !(*this>=d);
}
// d1 + 10
Date operator+(int day)
{
if(day<0)
{
return (*this)-(-day);
}
Date ret(*this);
ret._day+=day;
while(ret._day>GetMonthDay(_year,_month))
{
int monthday=GetMonthDay(ret._year,ret._month);
ret._day-=monthday;
ret._month++;
if(ret._month==13)
{
ret._month=1;
ret._year+=1;
}
}
return ret;
}
Date& operator+=(int day)
{
return *this=*this+day;
}
Date operator-(int day)
{
if(day<0)
{
return (*this)+(-day);
}
Date tmp=*this;
tmp._day-=day;
while(tmp._day<=0)
{
if(tmp._month==1)
{
tmp._year--;
tmp._month=12;
}
else
{
tmp._month--;
}
tmp._day+=GetMonthDay(tmp._year,tmp._month);
}
return tmp;
}
Date& operator-=(int day)
{
return *this=*this-day;
}
int operator-(const Date& d)
{
Date tmp=*this;
Date src=d;
int count=0;
int Flag=1;
while(tmp!=src)
{
if(tmp>src)
{
++src;
++count;
}
else
{
++tmp;
--count;
Flag=-1;
}
}
return count*Flag;
}
//++d1
Date& operator++() // 前置
{
*this+=1;
return *this;
}
//d1++
Date operator++(int) // 后置
{
Date tmp(*this);
*this+=1;
return tmp;
}
Date operator--()
{
*this-=1;
return *this;
}
Date operator--(int)
{
Date tmp(*this);
*this-=1;
return tmp;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2018,3,23);
d1=d1+100;
d1.Show();
d1-=100;
d1.Show();
d1-=-10;
d1.Show();
d1+=-10;
d1.Show();
Date d2(2017, 11, 25);
d2--;
d2.Show();
d2++;
d2.Show();
int ret=d2-d1;
cout<<ret<<endl;
bool res=d2<d1;
cout<<res<<endl;
ret=d1>=d2;
cout<<ret<<endl;
Date d3;
d3=d2;
d3.Show();
//++d1; // d1.operator++(&d1);
//d1++; // d1.operator++(&d1, 0);
system("pause");
return 0;
}
日期类的实现
最新推荐文章于 2022-10-27 21:27:17 发布