本系列 C++ 相关文章 仅为笔者学习笔记记录,用自己的理解记录学习!C++ 学习系列将分为三个阶段:基础篇、STL 篇、高阶数据结构与算法篇,相关重点内容如下:
- 基础篇:类与对象(涉及C++的三大特性等);
- STL 篇:学习使用 C++ 提供的 STL 相关库;
- 高阶数据结构与算法篇: 手动实现自己的 STL 库 及 设计实现高阶数据结构,如 B树、B+树、红黑树等。
学习集:
本期内容:【C++ 基础篇:23】:运算符重载之关系运算符 [ > 、 < 、 >= 、 <= 、 != 、 == ] 重载
运算符重载的基础认识:C++ 学习 ::【基础篇:17】:C++ 类与对象:运算符重载介绍、运算符重载函数(类内与类外区别)写法及简单设计实现
目录:
1. 运算符重载函数写法回顾
2. 六大关系运算符重载设计思路(重要)
3. 六大关系运算符重载函数实现【以 Date 类为例】
- - 3.1 Date 类的基本设计
- - 3.2 六大关系运算符实现
4. 类中涉及 const 的常见问题!
5. 相关文章推荐
【 C++学习合集链接 】
1. 运算符重载函数写法回顾
- 运算符重载函数名(固定的!):operator
- 基本格式写法:函数返回值类型 operator 运算符 (参数链表){}
- 注:本期中的关系运算符返回值均为:bool(布尔类型)
2. 六大关系运算符重载设计思路
六大关系运算符:大于、小于、大于等于、小于等于、不等于、等于。它们的返回结果只有:是 / 否!
在敲代码练习阶段,我们可以一个一个把这六个运算符重载都自行实现一遍,但在实际开发中,我们考虑的因素很多,比如我们应该学会复用已有功能实现其他功能,防止代码出现大量相似度高冗余代码。故:此处结合运算符重载提供了一种设计思路来解决问题。
- 首先,已知两个比较对象的结果只有两种可能!无非就是:是或否!
- 其次,以大于为例,两个对象作比较,要么大于,要么不大于! 而不大于的情况有多种,比如:小于或等于!而刚好小于等于就是包含了这两种情况,也就是说:对大于的结果取反就是小于等于,即:可以用大于的功能来实现小于等于【 注意:不要单纯的说不大于就是小于! 】
- 设计方案:实现 > 和 == ,并复用这两种关系实现: < 、 >= 、 <= 、 !=
说明:
- 「大于等于」:即:「大于 或 等于」 或 「不小于」
- 「小于等于」:即:「小于 或 等于」 或 「不大于」
- 「小于」:即:「不大于 + 不等于」
- 「不等于」:即:「等于的取反」
- 此为笔者本文举例的设计方案,实际还有其他组合方式,读者可自行设计并使用代码实现!【注:关系运算符的写法具有通用性!】
3. 六大关系运算符重载函数实现
3.1 Date 类的基本设计
#include<iostream>
using std::cout;
using std::endl;
using std::cin;
class Date {
public:
Date(int year,int month, int day)
:_year(year),_month(month),_day(day)
{
}
void Print() {
cout << _year << "年" << _month << "月" << _day << "日" << endl;
/* 实现两个日期对象的大小比较 */
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;
}
private:
int _year;
int _month;
int _day;
};
int main() {
return 0;
}
3.2 六大关系运算符实现
以下是六种关系运算符的重载函数写法(模板)!
读者可自行思考:
- 其他实现方案!
- 为什么使用 const 和 引用
/* 大于运算符重载 */
bool Date::operator > (const Date& d) const
{
if (_year > d._year
|| _year == d._year && _month > d._month
|| _year == d._year && _month == d._month && _day > d._day) return true;
return false;
}
/* 等于运算符重载 */
bool Date::operator == (const Date& d) const {
return (_year == d._year && _month == d._month && _day == d._day);
}
/* 不等于运算符重载:对等于结果取反 */
bool Date::operator != (const Date& d) const {
return !(*this == d);
}
/* 小于运算符重载:既不大于也不等于 */
bool Date::operator < (const Date& d) const {
return !(*this == d) && !(*this > d);
}
/* 大于等于运算符重载:大于或等于 */
bool Date::operator >= (const Date& d) const {
return (*this > d) || (*this == d);
}
/* 小于等于运算符重载:不大于 */
bool Date::operator <= (const Date& d) const {
return !(*this > d);
}
4. 相关文章推荐
1. C++ 学习 ::【基础篇:11】:C++ 类的基本使用与非静态 this 指针(两个面试考点):类的空指针问题(this指针可以为空吗?) | this指针存在哪里?
2. 【C++ 基础篇:22】:类的 const 对象 与 const 成员函数/方法 以及 类中涉及 const 的常见问题!