C++实现日期类
说明
实现日期类的目的是为了让我们对前面的知识点有更加深入的理解,日期类的实现我们统一采用声明和定义分离的方式,声明写在Date.h文件中,函数定义写在Date.cpp中。
1、日期类的成员变量
日期类的成员变量就三个,年:year,月:month,日:day。为了区分类内成员变量和函数参数我们统一在前面加上_。
// Date.h
class Date
{
public:
private:
int _year;
int _month;
int _day;
};
2、Print函数
用来打印输出日期,方便我们进行调试,不对日期对象进行修改,可以加上const。
(当然我们后面还会重载<<和>>操作符)
// Date.h
void Print() const;
// Date.cpp
void Date::Print() const
{
cout << _year << "-" << _month << "-" << _day << endl;
}
3、构造函数
日期类的构造函数我们可以给成全缺省,这样方便我们进行初始化。因为输入的日期可能是非法日期,所以我们还需要对输入的日期进行判断,我们可以实现一个GetMonthDay接口,来获取对应月份的天数进行判断。
由于GetMonthDay只是对月份天数进行判断,并不进行值的修改,我们可以加上const,而构造函数在.h声明中给出全缺省,在.cpp中就不需要给出缺省值了。
// Date.h
int GetMonthDay(int year, int month) const;
Date(int year = 1, int month = 1, int day = 1);
// Date.cpp
int Date::GetMonthDay(int year, int month) const
{
static int monthDay[13] = {
0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int day = monthDay[month];
if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
{
day++;
}
return day;
}
Date::Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
if (!(_year >= 0
&& (_month > 0 && _month < 13)
&& (_day > 0 && _day < GetMonthDay(year, month))) )
{
cout << "非法日期:";
// 调用下面的打印日期函数
Print();
}
}
monthDay数组我们给出13个空间,1-12则对应每个月份的天数。需要注意闰年的2月份是29天,所以我们需要对月份和年份进行判断。
另外日期类的析构函数由于没有资源需要释放,所以可以不写。拷贝构造和赋值运算符重载也可以不写,因为默认的浅拷贝就可以。
4、六个比较函数
日期类是可以进行比较的,所以我们可以重载<、==、<=、>、>=、!=这六个操作符。而我们不必六个函数都实现一遍,只需要实现<、==或>、==即可,剩下四个直接复用。这六个操作符都是比较,不进行值的修改,所以都可以加上const。
// Date.h
bool operator<(const Date& d

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



