标题:日期的天数版本,差个判断闰年函数,总是无限递归,请高手指教!!!
只看楼主
韩雨航
Rank: 1
等 级:新手上路
帖 子:21
专家分:0
注 册:2012-1-12
结帖率:57.14%
 问题点数:0 回复次数:0 
日期的天数版本,差个判断闰年函数,总是无限递归,请高手指教!!!
//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;
}
         
搜索更多相关主题的帖子: void class include public return 
2012-03-16 21:42



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-363405-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.397551 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved