日期的天数版本,差个判断闰年函数,总是无限递归,请高手指教!!!
//date.h//#include<iostream>
using namespace std;
//-------------------
class Date
{
int absday;
//int year;
protected:
void ymd2i(int y,int m,int d);
static const int tians[];
void print(ostream& o);
bool isLeapyear()const;
public:
Date(const string& s);
Date(int n=1):absday(n){}
Date(int y,int m,int d){ymd2i(y,m,d);}
Date operator+(int n)const{return Date(absday+n);}
Date& operator+=(int n){absday+=n;return *this;}
Date& operator++(){return *this+=1;}
int operator-(Date& d)const{return absday-d.absday;}
friend ostream& operator<<(ostream& o, const Date& d) //Date& d引用!!!
{
d.print(o);
return o;
}
};
//date.cpp//
#include<iostream>
#include"date.h"
#include<iomanip>
using namespace std;
//----------------------
const int Date::tians[]={0,31,59,90,120,151,181,212,243,273,304,334}; //等号!!
//------------------------
void Date::ymd2i(int y,int m,int d)
{
if(y<1||m<1||m>12||d<1||d>31)
absday=1;return;
absday=(y-1)*365+(y-1)/4-(y-1)/100+(y-1)/400;
absday+=tians[m-1]+d+m>2&&isLeapyear();
}
bool Date::isLeapyear()const //const error C2662: 'isLeapyear' : cannot convert 'this' pointer from 'const class Date' to 'class Date &'
{
//int n=absday;
//for(int y=1;n>isLeapyear()+365;n-=isLeapyear()+365,y++); //l-value specifies const object const函数试图修改成员变量
//return !((year-1)%4&&!(year-1)%100||(year-1)%400);
}
Date::Date(const string& s)
{
int y=atoi(s.substr(0,4).c_str());
int m=atoi(s.substr(5,2).c_str());
int d=atoi(s.substr(8,2).c_str());
ymd2i(y,m,d);
}
void Date::print(ostream& o)
{
int n=absday>0&&absday<3650000 ? absday:1; //d.absday
int m,day;
for(y;n>isLeapyear()+365;n-=isLeapyear()+365,y++);
for(m=1;n>(isLeapyear()&&m>2+tians[m]);m++); //无限循环了??、???
day=n-isLeapyear()&&m>2-tians[m-1];
o<<setfill('0')<<setw(4)<<y<<'-'<<setw(2)<<m<<'-'<<setw(2)<<day<<setfill(' ');
}
#include<iostream>
#include"date.h"
using namespace std;
int main()
{
Date d("2012-02-12");
cout<<d<<endl; //cout管输出到屏幕,<<重载了~~~
Date a(32113);
cout<<a<<endl;
cout<<d-a<<endl;
}