实验目的:设计一个DateTime类,显示相应的日期。
实验代码:
#include <iostream>
using namespace std;
class DateTime
{
public:
void set_DateTime();
void show_DateTime();
private:
bool is_DateTime(int, int, int);
int year;
int month;
int day;
};
int main()
{
DateTime d1;
DateTime &d2 = d1;
d1.set_DateTime();
d2.show_DateTime();
return 0;
}
void DateTime::set_DateTime()
{
char c1, c2;
cout << "请输入日期(格式yy:mm:dd)";
while(1)
{
cin >> year >> c1 >> month >> c2 >> day;
if(c1 != ':' || c2 != ':')
cout << "格式不正确,请重新输入" << endl;
else if(!is_DateTime(year, month, day))
cout << "时间非法,请重新输入" << endl;
else
break;
}
}
void DateTime::show_DateTime()
{
cout << year << ":" << month << ":" << day << endl;
}
bool DateTime::is_DateTime(int y, int m, int d)
{
if(y < 0 || m <= 0 || m > 12)
return false;
else if((y % 4 == 0 && y % 100 !=0) || y % 400 == 0)
{
if(m == 2 && (d <=0 || d > 29))
return false;
}
else if(m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12)
{
if(d <= 0 || d > 31)
return false;
}
else if(m == 2 && (d <= 0 || d > 28))
return false;
else if(d <=0 || d > 30)
return false;
return true;
}
实验结果代码: