//---------main.cpp------------
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class Date
{
private:
int year,month,day;
//void init();
public:
Date(int y=2000,int m=1,int d=1);//设置构造函数的默认参数
Date(const string &s);//重载构造函数
bool isLeapYear();
void print();
private:
void init();
};
void Date::init()
{
if(year>5000 || year<1 || month<1 || month>12 || day<1 || day>31) exit(1); //校验函数 停机
}
Date::Date(int y,int m,int d)
{
year = y;
month = m;
day=d;
init();
}
Date::Date(const string &s)
{
year = atoi(s.substr(0,4).c_str());
month = atoi(s.substr(5,2).c_str());
day = atoi(s.substr(8,2).c_str());
init();
}
bool Date::isLeapYear()
{
return(((year%4 == 0)&&(year%100 != 0))||(year%400 == 0));
}
void Date::print()
{
std::cout<<"the year is : "<<year<<"/"<<month<<"/"<<day<<endl;
}
int main(int argc,char **argv)
{
Date c("2004-12-28"); //构造函数中如果没有const,这里就报错,不知道为什么??
Date d(2012,12,30);
Date e(2014,12); //默认两个参数
Date f(2010); //默认一个参数
Date g; //
c.print();
d.print();
e.print();
f.print();
g.print();
}
the year is : 2004/12/28
the year is : 2012/12/30
the year is : 2014/12/1
the year is : 2010/1/1
the year is : 2000/1/1
请按任意键继续. . .
void Date::init()为校验函数;
1