c++ 计算时间的date类

本文介绍了一个使用C++实现的日期计算类,该类能够处理日期加减运算,并考虑了不同月份天数及闰年情况。通过示例展示了如何创建日期对象并进行日期的加减操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

计算时间的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;


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值