用C++實現一個日期類
阿新 • • 發佈:2019-01-04
最近在複習C++的時候發現日期類是一個非常有用的類,在現實中是非常實用的(雖然我不知道為什麼這麼實用的類,庫裡沒有)以下是我自己實現的日期類的程式碼,因為大部分都是運算子的過載,所以理解起來應該並不難
#include <iostream> #include <assert.h> using namespace std; class Date { friend ostream& operator<<(ostream& out,const Date& d); friend istream& operator>>(istream& in, Date& d); public: Date (int year=1900,int month=1,int day=1) { _year=year; _month=month; _day=day; if (month<1||month>12 ||day<1||day>GetMonthDay(year,month)) { assert (false); } } Date(const Date& d) { _year=d._year; _month=d._month; _day=d._day; } Date& operator=(const Date& d) { if (this!=&d) { _year=d._year; _month=d._month; _day=d._day; } return *this ; } bool IsLeapYear(int year) { if ((year%4==0&&year%100!=0)||year%400==0) { return true; } return false; } int GetMonthDay(int year,int month) { assert (month > 0 && month < 13); static int monthdays[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; int day=monthdays[month]; if (month==2&&IsLeapYear(year)) day+=1; return day; } bool operator<(const Date& d) { if ((_year<d._year) ||(_year==d._year&&_month<d._month) ||(_year==d._year&&_month==d._month&&_day<d._day)) { return true; } return false; } bool operator>(const Date& d) { return !(*this <=d); } bool operator<=(const Date& d) { return *this<d||*this==d; } bool operator>=(const Date& d) { return !(*this <d); } bool operator==(const Date& d) { return _year==d._year&&_month==d._month&&_day==d._day; } bool operator!=(const Date& d) { return !(*this ==d); } Date operator+ (int day) { if (day<0) { return *this-(-day); } Date ret(*this); ret._day+=day; while (ret._day>GetMonthDay(ret._year,ret._month)) { ret._day-=GetMonthDay(ret._year,ret._month); ret._month++; if (ret._month==13) { ret._year++; ret._month=1; } } return ret; } Date operator- (int day) { if (day<0) { return *this +(-day); } Date ret (*this ); ret._day-=day; while (ret._day<=0) { ret._month--; if (ret._month==0) { ret._year--; ret._month=12; } ret._day+=GetMonthDay(ret._year,ret._month); } return ret; } Date& operator+=(int day) { *this =*this +day; return *this; } Date& operator -=(int day) { *this =*this -day; return *this ; } Date& operator++() { *this +=1; return *this ; } Date operator++(int) { Date tmp(*this ); *this+=1; return tmp; } int operator-(const Date& d) { int flag=1; Date max=*this,min=d; if (*this <d) { max=d; min=*this; flag=-1; } int days=0; while (min<max) { ++min; ++days; } return days*flag; } void Show () { cout<<(*this)._year<<"-"<<_month<<"-"<<_day<<endl; } private: int _year; int _month; int _day; }; ostream& operator<<(ostream& out,const Date& d) { out<<d._year<<"-"<<d._month<<"-"<<d._day<<endl; return out; } istream& operator>>(istream& in, Date& d) { in>>d._year; in>>d._month; in>>d._day; return in; } void TestDate() { Date d1(2018,3,15); d1+=100; d1.Show(); } int main () { TestDate(); return 0; }