【C++】日期类+日期万年历+日期计算器
对于日期类,我们主要实现一下日期类的基本函数,构造,拷贝构造,运算符的重载,析构。当然这里运算符的重载需要实现的还是挺多的,如:=、<、>、<=、>=、等
#include<iostream>usingnamespacestd;classDate{public:Date(intyear=1990,intmonth=1,intday=1){_year=year;_month=month;_day=day;}Date(constDate&d){_year=d._year;_month=d._month;_day=d._day;}~Date(){}//万年历booloperator==(constDate&d){returnthis->_year==d._year&&this->_month==d._month&&this->_day==d._day;}booloperator<(constDate&d){if(_year<d._year){returntrue;}else{if(_year==d._year){if(_month<d._month){returntrue;}else{if(_month==d._month){if(_day<d._day){returntrue;}}}}}returnfalse;}booloperator<=(constDate&d){return!(*this>d);}booloperator>(constDate&d){if(_year>d._year){returntrue;}else{if(_year==d._year){if(_month>d._month){returntrue;}else{if(_month==d._month){if(_day>d._day){returntrue;}}}}}returnfalse;}booloperator>=(constDate&d){return!(*this<d);}
对于实现日期计算器,我们主要考虑的是加天数和减天数,那么问题就来了,对于加法,如果加的日期超过当前月的天数就需要考虑月的进位,对于年来说,如果月份大于12就需要重置为1,年进位。还需要考虑的一个问题就是,是否为闰年的2月份天数不同,那么应该如何解决呢?我们用一个数组把每个月的天数给保存起来,然后写一个判断闰年的函数,如果是闰年就在数组对应的2月上加上1天。对于减法,就相当于加上一个负天数,问题和加法一样。
//日期计算器Dateoperator+(intday);Dateoperator+=(intday);Dateoperator-(intday){this->_day-=day;while(_day<0){_day+=GetMonthDay(2016,3);_month-=1;if(_month<1){_month=12;_year-=1;}}return*this;}Dateoperator-=(intday);Dateoperator++();Dateoperator++(int);Dateoperator--();Dateoperator--(int);intoperator-(constDate&d);//计算器Date&calendar(intday=0){if(day>0)//加正天数{this->_day+=day;while(_day>GetMonthDay(2016,2)){_day-=GetMonthDay(2016,2);_month+=1;if(_month>12){_month=1;_year+=1;}}}else//加负天数{this->_day-=day;while(_day<0){_day+=GetMonthDay(2016,3);_month-=1;if(_month<1){_month=12;_year-=1;}}}return*this;}private:boolIsLeapYear(intyear){if(((year%4==0)&&(year%100!=0))||(year%400==0)){returntrue;}returnfalse;}intGetMonthDay(intyear,intmonth){intmonthArray[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};intday=monthArray[month];if(month==2&&IsLeapYear(year)){day+=1;}returnday;}private:int_year;int_month;int_day;
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。