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

相关推荐
持之以恒的天秤7 分钟前
线程同步学习
linux·学习
zh_xuan7 分钟前
c++ 类的语法3
开发语言·c++
Lester_11018 分钟前
嵌入式学习笔记 - STM32 ADC 模块工作模式总结
笔记·学习
一律清风1 小时前
【Opencv】canny边缘检测提取中心坐标
c++·opencv
a东方青5 小时前
蓝桥杯 2024 C++国 B最小字符串
c++·职场和发展·蓝桥杯
小Tomkk5 小时前
2025年PMP 学习十五 第10章 项目资源管理
学习·pmp·项目pmp
oceanweave6 小时前
【K8S学习之生命周期钩子】详细了解 postStart 和 preStop 生命周期钩子
学习·kubernetes
XiaoyaoCarter6 小时前
每日一道leetcode
c++·算法·leetcode·职场和发展·二分查找·深度优先·前缀树
galaxy_strive7 小时前
qtc++ qdebug日志生成
开发语言·c++·qt
Darkwanderor7 小时前
c++STL-list的模拟实现
c++·list