C++实现日期类(Date类)的方法
如下所示:
#include<iostream> usingnamespacestd; classDate { public: Date(intyear=1900,intmonth=1,intday=1)//构造 :_year(year) ,_month(month) ,_day(day) { if(!isInvalidDate(_year,_month,_day)) { _year=1900; _month=1; _day=1; } } Dateoperator+(intcount) { Datetmp(*this); tmp._day+=count; ToCorrect(tmp); returntmp; } Dateoperator-(intcount) { Datetmp(*this); tmp._day-=count; ToCorrect(tmp); returntmp; } Date&operator++()//前置++ { (*this)++; return*this; } Dateoperator++(int)//后置++ { Datetmp(*this); (*this)+=1; returntmp; } Date&operator--() { (*this)--; return*this; } Dateoperator--(int) { Datetmp(*this); (*this)--; returntmp; } intoperator-(constDate&d) { intflag=1; Datemax=*this; Datemin=d; if(*this<d) { max=d; min=*this; flag=-1; } intcount=0; while(min!=max) { ++min; count++; } returncount*flag; } Date&operator+=(intday) { *this=*this+day; return*this; } booloperator!=(constDate&d) { return!(*this==d); } booloperator<(constDate&d) { return!((*this>d)||(*this==d)); } booloperator>=(constDate&d) { return!(*this<d); } booloperator>(constDate&d) { return(_year>d._year ||(_year==d._year&&_month>d._month) ||(_year==d._year&&_month==d._month&&_day>d._day)); } booloperator==(constDate&d) { return((_year==d._year)&&(_month==d._month)&&(_day==d._day)); } public: boolIsLeapYear(intyear) { if(year%400||(year%4&&year%100)) returntrue; returnfalse; } intYearsOfMonth(intyear,intmonth) { intday; intdays[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; day=days[month]; if(month==2) day+=IsLeapYear(year); returnday; } DateToCorrect(Date&d) { if(d._day>YearsOfMonth(d._year,d._month)) { while(d._day>YearsOfMonth(d._year,d._month)) { d._day-=YearsOfMonth(d._year,d._month); if(d._month==12) { d._year++; d._month=1; } else { ++d._month; } } } else { while(d._day<=0) { if(d._month==1) { d._year--; d._month=12; } else { --d._month; } d._day+=YearsOfMonth(d._year,d._month); } } returnd; } boolisInvalidDate(intyear,intmonth,intday) { if((year<1)||(month<0||month>12)||(day<0||day>YearsOfMonth(year,month))) returnfalse; returntrue; } voidDisplay() { cout<<_year<<"-"<<_month<<"-"<<_day<<endl; } friendistream&operator>>(istream&is,Date&d); friendostream&operator<<(ostream&os,constDate&d); private: int_year; int_month; int_day; }; istream&operator>>(istream&is,Date&d) { cout<<"请输入一个日期"<<endl; is>>d._year>>d._month>>d._day; returnis; } ostream&operator<<(ostream&os,constDate&d) { cout<<d._year<<"-"<<d._month<<"-"<<d._day<<endl; returnos; } intmain() { /*Dated1(2016,8,18); //d1.Display(); //d1=d1++; cout<<d1<<endl;*/ //Dated1(2015,12,3); //(d1++).Display();//d1.operator++(&d1,0); //(++d1).Display();//d1.operator++(&d1); Dated1(2015,12,3); Dated2(2015,11,1); cout<<(d1-d2)<<endl; //Dated1(2015,12,3); //Dateret=d1+40;//operator+ //ret.Display(); /*Dated1(2015,12,3); Dateret=d1+40; d1=ret; ret=d1-40; ret.Display();*/ /*Dateret; Dated2(2015,1,1); ret=d2-1; ret.Display();*/ return0; }
以上这篇C++实现日期类(Date类)的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。