C++学习Day05之关系运算符重载

目录


一、程序及输出

1.1 ==运算符重载

c 复制代码
#include<iostream>
using namespace std;

class  Person
{
public:
	Person(string name, int age)
	{
		this->m_Name = name;
		this->m_Age = age;
	}

	bool operator==( Person & p)
	{
		if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
		{
			return true;
		}
		return false;
	}

	string m_Name;
	int m_Age;
};
void test01()
{

	Person p1("Tom", 18);

	Person p2("Tom", 19);

	if (p1 == p2)
	{
		cout << "p1 == p2 " << endl;
	}	
	else
	{
		cout << "p1 != p2 " << endl;
	}
}


int main(){
	test01();
	system("pause");
	return EXIT_SUCCESS;
}

输出:

1.2 !=运算符重载

c 复制代码
#include<iostream>
using namespace std;

class  Person
{
public:
	Person(string name, int age)
	{
		this->m_Name = name;
		this->m_Age = age;
	}

	bool operator!=(Person & p)
	{
		return !(this->m_Name == p.m_Name && this->m_Age == p.m_Age);
	}


	string m_Name;
	int m_Age;
};
void test01()
{
	Person p1("Tom", 18);
	Person p2("Tom", 19);

	if (p1 != p2)
	{
		cout << "p1 != p2 " << endl;
	}
	else
	{
		cout << "p1 == p2 " << endl;
	}

}


int main(){
	test01();
	system("pause");
	return EXIT_SUCCESS;
}

输出:


二、分析与总结

在 C++ 中,关系运算符重载允许我们自定义类的对象在进行比较操作(如相等性、大小比较)时的行为。通过重载关系运算符,我们可以定义对象之间的比较规则。

关系运算符重载的语法: 关系运算符重载通常采用成员函数或友元函数的形式,其一般形式为 bool operator==(const ReturnType& other) 或 bool operator<(const ReturnType& other)。其中 ReturnType 是类的类型,other 是要比较的对象。
关系运算符的返回类型: 关系运算符重载通常返回一个 bool 类型的值,表示比较的结果,通常为真(true)或假(false)。
关系运算符的实现: 在关系运算符重载函数中,通常需要根据类的数据成员进行比较操作,然后返回比较结果。可以根据具体的比较规则来实现相等性比较、大小比较等操作。
常用的关系运算符重载

相等性比较:bool operator==(const ReturnType& other)

不等性比较:bool operator!=(const ReturnType& other)

大小比较:bool operator<(const ReturnType& other)、bool operator>(const ReturnType& other)、bool operator<=(const ReturnType& other)、bool operator>=(const ReturnType& other)
友元关系运算符重载: 如果需要访问类的私有成员进行比较操作,可以将关系运算符重载函数声明为友元函数。
自定义比较规则: 在实现关系运算符重载时,可以根据具体的需求定义对象之间的比较规则,例如按照某个属性进行比较、按照特定的顺序进行比较等。

相关推荐
2301_8076114934 分钟前
77. 组合
c++·算法·leetcode·深度优先·回溯
微网兔子1 小时前
伺服器用什么语言开发呢?做什么用什么?
服务器·c++·后端·游戏
YuforiaCode1 小时前
第十三届蓝桥杯 2022 C/C++组 修剪灌木
c语言·c++·蓝桥杯
YOULANSHENGMENG2 小时前
linux 下python 调用c++的动态库的方法
c++·python
CodeWithMe2 小时前
【C++】STL之deque
开发语言·c++
电子云与长程纠缠2 小时前
Unreal Niagara制作SubUV贴图翻页动画
学习·ue5·编辑器·贴图·niagara
炯哈哈2 小时前
【上位机——MFC】运行时类信息机制
开发语言·c++·mfc·上位机
xing_x_xx3 小时前
Linux系统学习----概述与目录结构
学习
DKPT3 小时前
常见正则表达式整理与Java使用正则表达式的例子
java·笔记·学习·面试·正则表达式
rigidwill6664 小时前
LeetCode hot 100—最长有效括号
数据结构·c++·算法·leetcode·职场和发展