C/C++实现日期计算器的示例代码
问题介绍:
今天突然看到一个问题看起来蛮有趣的,跟大家分享一下.给定任意日期对该日期进行加减天数,最后得出加减后出现的日期.以及给两个日期你可以得出他们两个之间相隔多少天.(需要考虑闰年,每个月天数不同,我们需要写一个我们直接可以使用的日期加减器)因为时间比较仓促,我也没有写界面,只有其中几个主要的函数的架构思想以及简单的调试就发出来了.
代码实现:
#include#include #include usingnamespacestd; classDate { public: Date(intyear=1997,intmonth=1,intday=1) :years(year) ,months(month) ,days(day) { assert(IScorrect()); } Date&operator=(constDate&d) { if(this!=&d) { years=d.years; months=d.months; days=d.days; } return*this; } Date&operator+(intday) { while(day>365) { if(ISleapyear()&&day>366) { years++; day=day-366; } else { years++; day=day-365; } } while(day>=Getmonthsday()) { //注意这里的次序问题,一定先减再加最后再判断.如果顺序错了会出BUG的. day=day-Getmonthsday(); months++; if(months>12) { years++; months=1; } } while(day>0) { DateAdvance(); day=day-1; days++; } return*this; } Date&operator-(intday)//先减去一年,然后在使用加的重载,所以你只需要写一个无懈可击的加算法就够了. { while(day>365) { if(ISleapyear()&&day>366) { day=day-366; years--; } else { day=day-365; years--; } } if(ISleapyear()) { day=366-day; years--; } else { day=365-day; years--; } operator+(day); return*this; } voidDateAdvance()//用于出现可以进化的情况 { if(days>Getmonthsday()) { months++; days=1; } if(months>12) { years++; months=1; } } intoperator-(DateD) { intcount=0; if(*this>D) { while(*this!=D) { D.operator+(1); count++; } } else { while(*this!=D) { operator+(1); count++; } } returncount; } boolISleapyear() { if((years%4==0&&years%100!=0)||(years%400==0)) { returntrue; } returnfalse; } intGetmonthsday() { intmonthDays[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; if(ISleapyear()&&months==2) { return29; } returnmonthDays[months]; } voidprint() { cout<<"目前的时间为"; cout< 0&&((years%4==0&&years%100!=0)||(years%400==0))&&days<367)//闰年 { if(months>0&&months<13) { if(days>0&&days<=Getmonthsday()) { returntrue; } } } elseif(years>0&&days<366)//非闰年 { if(months>0&&months<13) { if(days>0&&days<=Getmonthsday()) { returntrue; } } } returnfalse; } Dateoperator+=(intday) { *this=*this+100; return*this; } Dateoperator-=(intday) { return*this=*this-day; } inlineDate&operator++() { *this+=1; return*this; } inlineDateoperator++(int) { Datetmp(*this); *this=*this+1; returntmp; } booloperator==(constDate&d) { return(years==d.years&&months==d.months&&days==d.days); } booloperator!=(constDate&d) { return!(*this==d); } booloperator>(constDate&d) { if(years>d.years|| (years==d.years&&months>d.months) ||(years==d.years&&months==d.months&&days>d.days)) { returntrue; } returnfalse; } booloperator<(constDate&d) { return!(*this>d); } booloperator>=(constDate&d) { return(*this==d)&&(*this>d); } booloperator<=(constDate&d) { return(*this==d)&&(*this 总结:
日期类对我们掌握面向对象这里还是一个蛮重要的知识,你至少要能很熟练很正确地自己快速写出这个整个框架,然后一个一个实现函数,我只能说很重要,很重要,很重要大家一定要掌握.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。