实现一个CDate类

classCDate{public:CDate(intyear=1900,intmonth=1,intday=1):_year(year),_month(month),_day(day){if(!(_year>=1900&&(_month>0&&_month<13)&&(_day>0&&_day<=_GetMonthDay(_year,_month)))){_year=1900;_month=1;_day=1;}}boolIsLeap(intyear)//判断闰年{if((year%4==0&&year%100!=0)||(year%400==0)){returntrue;}returnfalse;}private:int_GetMonthDay(intyear,intmonth){intdays[]={0,31,28,31,30,31,30,31,31,30,31,30,31};if(IsLeap(year)&&month==2)//闰年并且月份为2{days[month]+=1;}returndays[month];}private:int_year;int_month;int_day;};


完成CDate类的几个函数

#include<iostream>usingnamespacestd;classCDate{public:CDate(intyear=1900,intmonth=1,intday=1):_year(year),_month(month),_day(day){if(!(_year>=1900&&(_month>0&&_month<13)&&(_day>0&&_day<=_GetMonthDay(_year,_month)))){_year=1900;_month=1;_day=1;}}//比较日期booloperator<(constCDate&d){if(_year<d._year){returntrue;}elseif(_year==d._year&&_month<d._month){returntrue;}elseif(_year==d._year&&_month==d._month&&_day<d._day){returntrue;}returnfalse;}booloperator==(constCDate&d){return(_year==d._year&&_month==d._month&&_day==d._day);}booloperator>(constCDate&d){return(!(*this<d||*this==d));}//日期加法CDateoperator+(intday){if(day<0){return*this-(0-day);}CDatetemp(*this);temp._day+=day;while(temp._day>_GetMonthDay(temp._year,temp._month)){temp._day-=_GetMonthDay(temp._year,temp._month);if(temp._month==12){temp._year++;temp._month=1;}else{temp._month++;}}returntemp;}//日期减法CDateoperator-(intday){if(day<0){return*this+(0-day);}CDatetemp(*this);temp._day-=day;while(temp._day<=0){if(temp._month==1){temp._year--;temp._month=12;}else{temp._month--;}temp._day+=_GetMonthDay(temp._year,temp._month);}returntemp;}//前置加加CDate&operator++(){*this=*this+1;return*this;}//后置加加CDateoperator++(int){CDatetemp(*this);*this=*this+1;returntemp;}//前置减减CDate&operator--(){*this=*this-1;return*this;}//后置减减CDateoperator--(int){CDatetemp(*this);*this=*this-1;returntemp;}//两者作差intoperator-(constCDate&d){CDatemin(*this);CDatemax(d);if(min>max){min=d;max=*this;}intcount=0;while(min<max){min=min+1;count++;}returncount;}boolIsLeap(intyear){if((year%4==0&&year%100!=0)||(year%400==0)){returntrue;}returnfalse;}private:int_GetMonthDay(intyear,intmonth){intdays[]={0,31,28,31,30,31,30,31,31,30,31,30,31};if(IsLeap(year)&&month==2)//闰年并且月份为2{days[month]+=1;}returndays[month];}friendostream&operator<<(ostream&_cout,constCDate&d){_cout<<d._year<<"-"<<d._month<<"-"<<d._day;return_cout;}private:int_year;int_month;int_day;};intmain(){CDated(1992,1,26);cout<<d+4<<endl;cout<<d+34<<endl;cout<<d+10000<<endl;cout<<d-26<<endl;CDated1(1992,1,1);cout<<d-d1<<endl;cout<<d1-d<<endl;cout<<d1++<<endl;cout<<++d1<<endl;system("pause");return0;}