日期类的重载

Posted on 2006-05-18 19:21 可以重来 阅读(97) 评论(0)  编辑 收藏 引用

#include <iostream>
#include <iomanip>
class Date
{
   public:
     void SetDay(int y,int m,int d);
     friend Date &operator++(Date& a);
     friend Date operator++(Date& a,int );
     friend ostream& operator<<(ostream& o,const Date& t);
   protected:
     bool Legal(int y,int m,int d);
     bool IsLeapYear(int y);
     int year;
     int month;
     int day;
};

Date &operator++(Date& a)
{
  if(a.Legal(a.year,a.month,a.day+1))
    a.day++;
  else if(a.Legal(a.year,a.month+1,1))
   a.month++,a.day=1;
  else if(a.Legal(a.year+1,1,1))
    a.day=1,a.month=1,a.year++;
   return a;
}

Date operator++(Date& a,int)
{
  Date t(a);
  if(a.Legal(a.year,a.month,a.day+1))
    a.day++;
  else if(a.Legal(a.year,a.month+1,1))
   a.month++,a.day=1;
  else if(a.Legal(a.year+1,1,1))
    a.day=1,a.month=1,a.year++;
   return t;
}
void Date::SetDay(int y,int m,int d)
{   if(Legal(y,m,d))
    day=d,month=m,year=y;
}

ostream& operator<<(ostream& o,const Date& t)
{
 o<<setfill('0')<<setw(4)<<t.year<<"-"<<setw(2)
 <<t.month<<"-"<<setw(2)<<t.day<<"\n";
return o;
}

bool Date::Legal(int y,int m,int d)
{
  if(y>9999||y<1||d<1||m<1||m>12)
     return false;

     int dayLimit=31;
     switch(m) case 4: case 6: case 9: case 11: dayLimit--;
     if(m==2)
     dayLimit = IsLeapYear(y)? 29:28;

     return (d>dayLimit)? false:true;
}

bool Date ::IsLeapYear(int y)
 {
  return !(y%4)&&(y%100)||!(y%400);
 }

using namespace std;
int main()
{
Date a;
a.SetDay(2005,12,30);
cout <<a++;
cout <<++a;
}

 


只有注册用户登录后才能发表评论。
网站导航:   博客园   博客园最新博文   博问   管理


posts - 0, comments - 0, trackbacks - 0, articles - 1

Copyright © 可以重来