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

相关推荐
小灰灰爱代码32 分钟前
C++——求3*3矩阵对角元素之和。
数据结构·c++·算法
老K(郭云开)40 分钟前
allWebPlugin中间件自定义alert、confirm及prompt使用
c++·chrome·中间件·prompt·html5·edge浏览器
福鸦3 小时前
详解c++:new和delete
开发语言·c++
深蓝海拓3 小时前
迭代器和生成器的学习笔记
笔记·python·学习
createcrystal4 小时前
《算法笔记》例题解析 第3章入门模拟--3图形输出(9题)2021-03-03
c++·笔记·算法
tan77º5 小时前
【C++】异常
c++·算法
薛文旺6 小时前
c++可视化打印树
开发语言·c++
DogDaoDao6 小时前
Windows 环境下 vscode 配置 C/C++ 环境
c语言·c++·windows·vscode·gcc·mingw-w64
q4725994516 小时前
OpenGL 原生库6 坐标系统
c++
Once_day6 小时前
C++(2)进阶语法
c++