//日期的天数版本类文件 #ifndef HEADER_DATE_TWO #define HEADER_DATE_TWO #include <iostream> using namespace std; class Date_Two { int absday; int year, month, day; protected: //计算年月日的天数 void ymd2i(int y, int m, int d); static const int tians[]; bool isLeapYear(); //判断是否为闰年 public: //构造函数 Date_Two(const string& s); //构造函数 Date_Two(int n=1) : absday(n){} Date_Two(int y, int m, int d){ ymd2i(y,m,d); } //重载运算符+进行天数的添加 Date_Two operator+(int n)const{ return Date_Two(absday + n); } //重载加等运算符,返回对像自己 Date_Two& operator+=(int n){ absday +=n; return *this; } //重载++运算符,返回对像自己 Date_Two& operator++(){ return *this +=1;} //ostream& print(ostream& o); void print(ostream& o); int operator-(Date_Two& d)const{ return absday - d.absday; } friend ostream& operator<<(ostream& o, Date_Two& d); //friend std::ostream& operator<<(std::ostream& o, Date_Two& d); }; #endif;
//下面是日期的天数版本的程序代码 #include "date_two.h" #include <iostream> #include <iomanip> using namespace std; const int Date_Two::tians[]={0,31,59,89,120,150,181,212,242,273,303,334}; Date_Two::Date_Two(const string& s) { year = atoi(s.substr(0,4).c_str()); month = atoi(s.substr(5,2).c_str()); day = atoi(s.substr(8,2).c_str()); ymd2i(year,month,day); } void Date_Two::ymd2i(int y, int m, int d) { if(0<y || y>9999 || 0<m || m>12 || 0<d || d>31){ absday=1; return; } absday = (y-1)*365 + (y-1)/4 - (y-1)/100 + (y-1)/400; absday += tians[m-1] + (isLeapYear() && m>2) + d; } void Date_Two::print(ostream& o) { o<<setfill('0')<<setw(4)<<year<<"-"<<setw(2)<<month<<"-"<<setw(2)<<day<<"\n"<<setfill(' '); } bool Date_Two::isLeapYear() { return (year % 4 ==0 || year % 400 ==0) && (year % 100 != 0); } ostream& operator<<(ostream& o, Date_Two& d) { //absday = absday > 0 && absday d.print(o); return o; }
#include "date_two.h" #include <iostream> using namespace std; int main() { Date_Two d("2011-11-11"); cout<<d; system("pause"); return 0; }