在学C++类的时候,日期类是一个很基础也很重要的类,所以有必要实现一下。
常规日期类的本身并不复杂,实现的过程主要涉及到了一些构造函数,拷贝构造函数,以及各种运算符的重载等,而难点主要在于如何保证日期的有效性,比如我们知道年必须为正数,月都是1-12之间的整数,各个月的天数不同以及闰年2月天数的变化等等,如何将这些体现在我们对于一个日期类对象进行自增,自减以及加减多少天得出正确的日期等运算中。
下面先给出类的定义:
class Date {
friend ostream& operator<<(ostream& _cout, const Date& date);
friend istream& operator>>(istream& _cin, Date& date);
public:
Date(int year = 1990, int month = 1, int day = 1);
Date(const Date& date);
Date& operator=(const Date& date);
Date operator+(int day);
Date& operator++();
Date operator++(int);
Date operator-(int day);
int operator-(const Date& date);
Date& operator--();
Date operator--(int);
bool operator>(const Date& date);
bool operator<(const Date& date);
bool operator==(const Date& date);
bool operator!=(const Date& date);
bool operator>=(const Date& date);
bool operator<=(const Date& date);
private:
bool IsLeapYear(int year)
{
return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
}
int GetDaysInMonth(int year, int month)
{
int months[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (IsLeapYear(year)) {
months[2] = 29;
}
return months[month];
}
private:
int _year;
int _month;
int _day;
};
Date