声明一个Date类 重载运算符计算前一天和后一天日期 两个日期间的天数以及n天后的日期

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

#include<iostream.h>
#include<Cmath>
using namespace std;
class Date
{public:
Date(int y,int m,int d):year(y),month(m),day(d){}//构造函数
void ymdoutput();//输出日期
Date operator++(int);//重载自增求当前日期的下一天
Date operator--(int);//重载自减求当前日期的前一天
long double zongriqi();//间接求两个日期(重载-号没有想出来)
Date operator+(int);//重载+号求n天后的日期
private:
int year;
int month;
int day;};
void Date::ymdoutput()
{Date d(year,month,day);
cout<<d.year<<"/"<<d.month<<"/"<<d.day<<endl;}
Date Date::operator++(int)
{if((month==4||month==6||month==9||month==11)&&day==30)
{month++;
day=1;}
else if((month==1||month==3||month==5||month==7||month==8||month==10)&&day==31) {month++;
day=1;}
else if(month==12&&day==31)
{year++;
month=1;
day=1;}
else if(month==2)
{if((year/4==0&&year/100!=0||year/400==0)&&day==29)
{month++;
day=1;}
else if(day==28)
{month++;
day=1;}}
else day++;
return *this;}
Date Date::operator--(int)
{if((month-1==4||month-1==6||month-1==9||month-1==11)&&day==1)
{month--;
day=30;}
else
if((month-1==1||month-1==3||month-1==5||month-1==7||month-1==8||month-1==10)&&day ==1)
{month--;
day=31;}
else if(month==1&&day==1)
{year--;
month=12;
day=31;}
else if(month-1==2)
{if((year/4==0&&year/100!=0||year/400==0)&&day==1)
{month--;
day=29;}
else if(day==1)
{month--;
day=28;}}
else day--;
return *this;}
long double Date::zongriqi()
{long double s;
int i;
s=0;
for(i=0;i<year;i++)
{if(year/4==0&&year/100!=0||year/400==0)
s=s+366;
else s=s+365;}
for(i=0;i<month;i++)
{if(month==4||month==6||month==9||month==11)
s=s+30;
else if(month==1||month==3||month==5||month==7||month==8||month==10||month==12) s=s+31;
else if(month==2)
{if(year/4==0&&year/100!=0||year/400==0)
s=s+29;
else s=s+28;}}
s=s+day;
return s;}
Date Date::operator+(int n)
{int i;
for(i=1;i<=n;i++)
{if((month==1||month==3||month==5||month==7||month==8||month==10)&&day==31) {day=1;
month++;}
else if((month==4||month==6||month==9||month==11)&&day==30)
{day=1;
month++;}
else if(month==12&&day==31)
{day=1;
month=1;
year++;}
else if(month==2)
{if((year/4==0&&year/100!=0||year/400==0)&&day==29)
{day=1;
month++;}
else if(day==28)
{day=1;
month++;}}
else day++;}
return *this;}
int main(void)
{int a,b,c,n;
char x,y;
cout<<"请输入年月日,以逗号分隔";
cin>>a>>x>>b>>y>>c;
if(x!=','||y!=',')
{cout<<"输入格式错误,请重新输入";}
Date d(a,b,c);
cout<<"该日期的下一天为:";
Date d2(d);//拷贝构造函数
d2++;
d2.ymdoutput();
cout<<"该日期的前一天为:";
d2=d--;
d2.ymdoutput();
d++;
cout<<"再输入一个与之前日期比较的日期:";
cin>>a>>x>>b>>y>>c;
if(x!=','||y!=',')
{cout<<"输入格式错误,请重新输入";}
Date d1(a,b,c);
cout<<"两个日期相隔的天数为:";
cout<<abs(d.zongriqi()-d1.zongriqi())<<endl;
cout<<"输入n,求第一个日期n天后的日期:"; cin>>n;
cout<<"n天后的日期为:";
d1=d+n;
d1.ymdoutput();
system("pause");
return 0;}。

相关文档
最新文档