C++日期类Date的实现

在学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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值