定义一个满足下列要求的Date类:
①用下面的格式输出日期:日/月/年
②可运行在日期上加一天操作
③设置日期
#include"iostream"
using namespace std;
class Date{
private:
int year;
int month;
int day;
public:
void print();
void addOneDay();
bool setDate(int ,int, int);
private:
bool isValid(int, int, int);
bool isLeap(int);
};
void Date:: print()
{
cout<<day<<"/"<<month<<"/"<<year;
}
void Date:: addOneDay()
{
if (isValid(year,month,day+1))
day+=1;
else
if (isValid(year,month+1,1))
month++,day=1;
else
if (isValid(year+1,1,1))
year++,month=1,day=1;
}
bool Date:: setDate(int y,int m, int d)
{
if(isValid(y,m,d))
{year=y,month=m,day=d;return true;}
return false;
}
bool Date:: isValid(int y, int m, int d)
{
int dayLimit=31;
if (y>9999 || y<1 || m>12 || m<1 || d<1) return false;
switch(month)
{
case 4:
case 6:
case 9:
case 11:dayLimit--;break;
case 2:dayLimit=isLeap(y)?29:28;
}
return d<=dayLimit;
}
bool Date:: isLeap(int y)
{
if ((y%4==0 && y %100 !=0) || (y%400==0)) return true;
return false;
}
int main()
{
Date d;
int y ,m, r;
cin>>y>>m>>r;
while(!d.setDate(y,m,r))
{
cout<<"data error:";
cin>>y>>m>>r;
}
d.addOneDay();
d.print();
return 0;
}