C++从入门到入土(四)--日期类的实现

目录

前言

日期类的实现

日期的获取

日期的比较

const成员函数 

日期的加减

日期的加等

日期的减等

 日期的加减

日期的加加减减

日期的相减

流插入和提取的重载

友元

友元的特点

 日期类代码

 总结


前言

前面我们介绍了C++中类和对象的相关知识和六个默认成员函数,在此基础上我们可以用C++实现一个日期类,这样可以帮助我们更加深入理解C++中的知识点,如果文章中有不懂的可以参考之前的文章

C++从入门到入土(三)--6个默认成员函数

C++从入门到入土(二)——初步认识类与对象

日期类的实现

我们在创建一个项目之前首先要知道这个项目要完成什么功能,以日期类为例,我们要实现日期的比较,日期的加减,以及日期的获取等功能,所以根据之前学的运算符重载等方面的知识我们可以很轻松地在Date.h文件中声明这个类所要实现的各种功能,如下所示

#pragma once
#include
using namespace std;

class Date
{
	friend ostream& operator<<(ostream& out, const Date& d);
	friend istream& operator>>(istream& in, Date& d);
public:
	Date(int year = 1900, int month = 1, int day = 1);
	int GetMonthDay(int year, int month)
	{
		int GetMonthDayArry[13] = { 0,31,30,31,30,31,30,31,31,30,31,30,31 };
		if (2 == month && (year % 4 == 0 && year % 100 != 0 )|| year % 400 == 0)
		{
			return 29;
		}
		else
		{
			return GetMonthDayArry[month];
		}
	}
	bool CheckDate();
	void Print()const;
	bool operator<(const Date& d)const;
	bool operator<=(const Date& d)const;
	bool operator>(const Date& d)const;
	bool operator>=(const Date& d)const;
	bool operator==(const Date& d)const;
	bool operator!=(const Date& d)const;

	Date& operator+=(int day);
	Date operator+(int day)const;
	Date& operator-=(int day);

	int operator-(const Date& d)const;

	Date& operator++();
	Date operator++(int);
	Date& operator--();
	Date operator--(int);
private:
	int _year;
	int _month;
	int _day;
};

ostream& operator<<(ostream& out, const Date& d);
istream& operator>>(istream& in, Date& d);

 下面我将逐一分析实现相关的功能。

日期的获取

我们创建好一个日期类后,首先要获取里面的日期,于是我们创建了一个GetMonthDay的成员函数,可以看到,它的返回值是int,在函数里面我们创建了一个名为GetMonthDayArry的数组,这个数组里面存放了每个月的天数,为了方便通过传月份来获取日期我们给这个数组的数据个数定为13,但是我们此时面临一个问题:遇到闰年的2月该怎么办呢?那么此时我们就要特殊情况特殊处理,闰年的判断规则是:四年一润,百年不润,四百年再润,于是我们便可以轻松写下如下代码:

int GetMonthDay(int year, int month)
{
	int GetMonthDayArry[13] = { 0,31,30,31,30,31,30,31,31,30,31,30,31 };
	if (2 == month && (year % 4 == 0 && year % 100 != 0 )|| year % 400 == 0)
	{
		return 29;
	}
	else
	{
		return GetMonthDayArry[month];
	}
}

日期的比较

通过运算符重载的相关知识我们

你可能感兴趣的:(c++,开发语言)