创建一个Date.h文件用来声明Date日期类的类,以便管理。
class Date
{
public:
//构造函数
Date(int year = 1, int month = 1, int day = 1);
void Print();
bool operator>(const Date& d);
bool operator<(const Date& d);
bool operator>=(const Date& d);
bool operator<=(const Date& d);
bool operator==(const Date& d);
bool operator!=(const Date& d);
Date& operator+=(int day);//d1+=100
Date operator+(int day);//d1+100
Date& operator-=(int day);//d1-=100
Date operator-(int day);//d1-100
private:
int _year;
int _month;
int _day;
};
这里是我们要实现的成员函数。
创建一个Date.cpp源文件,包头文件
#include "Date.h"
构造函数
众所周知缺省函数在头文件声明的话,就不能在源文件中声明,二者只能声明一个,且只能在头文件.h中使用缺省参数。
Date::Date(int year,int month,int day)
{
_year = year;
_month = month;
_day = day;
}
并写出打印函数
void Date::Print()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
测试一下
void DateTest1()
{
Date d1;
Date d2(2022, 1, 16);
d1.Print();
d2.Print();
Date d3(2022, 13, 15);
d2.Print();
Date d4(2022, 2, 29);
d3.Print();
Date d5(2020, 2, 29);
d4.Print();
Date d6(2000, 2, 29);
d6.Print();
}
发现一些非法日期,比如上述的月份大于12,非闰月天数为29,这种非法日期。,所以需要在构造函数初始化的时候判断日期合法性。
【判断方法】
如果year大于0,month大于0,小于13,day大于0,小于该月的天数,及为合法,那么想要获得该月的天数,我们写一个函数获取该月的天数。
写一个数组,传入月数,即可获得该月的天数,那么2月还需要判断一下,是否是闰年。
润年