本文主要是介绍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;
}
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;
}
这篇关于c++ 计算时间的date类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!