C++ - Date
1、使用C++ 实现一个Date类
namespace Chrono{
class Date{
public:
enum Month{
jan=1,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec
};
class Invalid{}; //to throw as exception
Date(int y,Month m,int d);
Date();
int day() const {return d;}
Month month() const {return m;}
int year() const {return y;}
void add_day(int n);
void add_month(int n);
void add_year(int n);
private:
int y;
Month m;
int d;
};
/* helper functions: */
bool is_date(int y,Date::Month m,int d);
bool leapyear(int y); //是否闰年
bool operator==(const Date& a,const Date& b);
bool operator!=(const Date& a,const Date& b);
istream& operator>>(istream& is,Date& dd);
ostream& operator<<(ostream& os,const Date& d);
}
#include "chrono.h" namespace Chrono{ Date::Date(int yy,Month mm,int dd):y(yy),m(mm),d(dd) { if(!is_date(yy,mm,dd)) throw Invalid(); } //default_date() 用来代替全局变量 Date& default_date(){ static Date dd(2000,Date::jan,1); return dd; } int days_in_month(int y,Date::Month m){ switch(m){ case Date::feb: return (leapyear(y))?29:28; case Date::apr: case Date::jun: case Date::sep: case Date::nov: return 30; default: return 31; } } Date::Date() :y(default_date().year()), m(default_date().month()), d(default_date().day()) { } void Date::add_day(int n){ while(n>=days_in_month(y,m)){ n-=days_in_month(y,m); add_month(1); } if(d+n>days_in_month(y,m)){ d=d+n-days_in_month(y,m); add_month(1); }else{ d+=n; } } void Date::add_month(int n){ bool flag=d==days_in_month(y,m); while(n>0){ if(m==dec){ m=jan; add_year(1); }else{ m=(enum Month)(m+1); } n--; } if(flag){ d=days_in_month(y,m); } } void Date::add_year(int n){ if(m==feb&&d==29&&!leapyear(y+n)){ m=mar; //use March 1 instead of feb 29 d=1; } y+=n; } bool is_date(int y,Date::Month m,int d){ if(d<=0) return false; if(d>days_in_month(y,m)) return false; return true; } bool leapyear(int y){ if(y<=0) return false; if(y%4==0){ if(y%100==0 && y%400!=0) return false; return true; } return false; } bool operator==(const Date& a,const Date& b){ return a.year()==b.year() && a.month()==b.month() && a.day()==b.day(); } bool operator!=(const Date& a,const Date& b){ return !(a==b); } istream& operator>>(istream& is,Date& dd){ int y,m,d; char ch1,ch2,ch3,ch4; is>>ch1>>y>>ch2>>m>>ch3>>d>>ch4; if(!is) return is; if(ch1!='('||ch2!=','||ch3!=','||ch4!=')'){ is.clear(ios_base::failbit); return is; } return is; } ostream& operator<<(ostream& os,const Date& d){ return os<<'('<<d.year() <<','<<d.month() <<','<<d.day()<<')'; } }
浙公网安备 33010602011771号