c++ 計算時間的date類

計算時間的date類

代碼:
#include<iostream>
using namespace std;
class Date{
private:
int year;
int month;
int day;
public:
Date(int y=0,int m=0,int d=0);
~Date(){}
Date &operator +(int days);
Date &operator -(int days);
int month_days();
void show();
};
Date::Date(int y,int m,int d):year(y),month(m),day(d){

}
int Date::month_days(){
if(month==1||month==3||month==5||month==7||month==8||month==10||month==12){return 31;}
if(month==2){
if((year%4==0&&year%100!=0)||year%400==0)
return 29;
else return 28;
}
return 30;
}
Date &Date::operator+(int days){
day=day+days;
while(day>month_days()){
day=day-month_days();
month+=1;
if(month>12){
month=1;
year+=1;
}
}
return *this;
}
Date &Date::operator-(int days){
day=day-days;
while(day<=0){
day=day+month_days();
month-=1;
if(month<=0){
month=12;
year-=1;
}
}
return *this;
}
void Date::show(){
cout<<"現在是"<<year<<"年"<<month<<"月"<<day<<"日"<<endl;
}
int main()
{
cout<<"hello world"<<endl;
cout<<"this is my frist linux c++ program"<<endl;
Date d1(2012,5,22);
d1.show();
d1=d1+730;
d1.show();
d1=d1-730;
d1.show();
return 0;


}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章