本篇文章我们将实现下面下面这些函数接口:

代码语言:javascript

AI代码解释

class Date
{
public:
	// 获取某年某月的天数
	int GetMonthDay(int year, int month);
	// 全缺省的构造函数
	Date(int year = 1900, int month = 1, int day = 1);
	// 拷贝构造函数
    //d2(d1) 
	Date(const Date& d);
	// 赋值运算符重载
    // d2 = d3 -> d2.operator=(&d2, d3)
	Date& operator=(const Date& d);
	// 析构函数
	~Date();
	// 日期+=天数
	Date& operator+=(int day);
	// 日期+天数
	Date operator+(int day);
	// 日期-天数
	Date operator-(int day);
	// 日期-=天数
	Date& operator-=(int day);
	// 前置++
	Date& operator++();
	// 后置++
	Date operator++(int);
	// 后置--
	Date operator--(int);
	// 前置--
	Date& operator--();
	// >运算符重载
	bool operator>(const Date& d);
	// ==运算符重载
	bool operator==(const Date& d);
	// >=运算符重载
	inline bool operator >= (const Date& d);
	// <运算符重载
	bool operator < (const Date& d);
	// <=运算符重载
	bool operator <= (const Date& d);
	// !=运算符重载
	bool operator != (const Date& d);
	// 日期-日期 返回天数
	int operator-(const Date& d);
 
private:
	int _year;
	int _month;
	int _day;
 
};

我们可以采用多文件的形式储存:


1. 全缺省的构造函数

构造函数其实就是初始化的一个过程,尤其注意的是对于日期的一个合法性的判断。但是因为月份的天数的细微差距,这里调用一个GetMonthDay()函数接口来完成:

代码语言:javascript

AI代码解释

int Date::GetMonthDay(int year, int month)
{
	assert(year >= 0 && month < 13 && month>0);
	//开辟一个静态区间,用来解决不同月份的天数不同
	static int monthDayAraay[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
	if (month == 2 && isLeapYear(month))
	{
		return 29;
	}
	return monthDayAraay[month];
}

这里因为月份对应的天数是固定的,所以我们选择将每个月的天数储存在一个静态数组中,这样一来就可以做到一次的开辟,之后可以进行多次的调用

同时因为二月天数收年份影响,所以这里继续编写一个判断是都为闰年的函数接口isLeapYear(),如果十二月份并且是闰年则直接返回29:

代码语言:javascript

AI代码解释

bool isLeapYear(int year)
{
	return (year % 100 != 0 && year % 4 == 0) || (year % 400 == 0);
}

上面就是我们应该在构造函数中进行的日期是否合法的判断,所以我们最终的构造函数应该是:

代码语言:javascript

AI代码解释

Date::Date(int year, int month, int day)
{
	if (year > 0 && month < 13 && month>0 && day > 0 && day <= GetMonthDay(year,month))
	{
		_year = year;
		_month = month;
		_day = day;
	}
	else
	{
		cout << "日期不合翻!" << endl;
		exit(-1);
	}
}

2. opeartor ==

判断两个日期是否相等很简单,只需要将年月日的比较结果进行与逻辑判断即可:

代码语言:javascript

AI代码解释

bool Date::operator == (const Date & d)
{
	return _year == d._year
		&& _month == d._month
		&& _day == d._day;
}

3. operator <

要想判断日期<日期:

  • 先比较year,如果year小的话,后面就无须比较了,直接返回ture
  • 如果year相等,就比较month,如果month小的话,后面也无须比较,直接返回ture
  • 如果year、month都相等时,最后才比较day,如果day小,直接返回ture
     
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐