🔥个人主页:Forcible Bug Maker
🔥专栏:C++
前言
日期类
日期类实现地图
获取某年某月的天数:GetMonthDay
检查日期合法,构造函数,拷贝构造函数,赋值运算符重载及析构函数
日期类的+=day和+day
日期类的-=day和-day
前置++和后置++
前置--和后置--
比大小运算符的重载
日期-日期返回天数
暴力++法
直接相减法
const成员
流插入和流提取重载
友元(friend)
结语
前言
本篇主要内容:日期类的实现
上篇我们介绍了拷贝构造函数和赋值运算符重载两大类的默认成员函数,本篇将会介绍更多关于操作符重载的实例运用。日期类,是与日期相关的类,主要用于处理与日期和时间相关的操作。我们将在完善一个日期类的过程中加深对运算符重载的理解和运用。在理解操作符重载之后,最后两个默认成员函数学习起来也就不是什么大问题了。
日期类
日期类实现地图
在实现日期类之前,需事先要知道要实现哪些内容。我会给出一份类的指南,也就是成员变量和成员函数的声明,然后根据声明一步步实现其中的成员函数。在代码编写过程中,成员函数是可以直接定义在类内部的;但是在实际开发过程中,考虑到工程级项目的规模,一般采用声明和定义分离的方式经行类的实现。将声明统一放在 Date.h 中,把成员函数的定义统一放在 Date.cpp 中,道理跟C语言的声明定义分离一样。
#include #include using namespace std; class Date { // 友元 friend ostream& operator(istream& in, Date& d); public: // 获取某年某月的天数 int GetMonthDay(int year, int month); // 检查日期是否合法 bool CheckDate(); // 全缺省的构造函数 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); // >=运算符重载 bool operator >= (const Date& d); // d._day) return true; return false; } // ==运算符重载 bool Date::operator==(const Date& d) { return _year == d._year && _month == d._month && _day == d._day; }
这里是对于>和==的重载,其中逻辑不难理解。
此时如果我们想要实现 >= ,直接复用上面两个重载就可以了。
// >=运算符重载 bool Date::operator>=(const Date& d) { return *this > d || *this == d; }
发现C++运算符重载和复用的魅力了吗?
如果此时你需要一个
//