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

相关推荐
九年义务漏网鲨鱼1 小时前
【大模型学习 | MINIGPT-4原理】
人工智能·深度学习·学习·语言模型·多模态
jz_ddk1 小时前
[学习] C语言数学库函数背后的故事:`double erf(double x)`
c语言·开发语言·学习
xiaolang_8616_wjl1 小时前
c++文字游戏_闯关打怪2.0(开源)
开发语言·c++·开源
夜月yeyue2 小时前
设计模式分析
linux·c++·stm32·单片机·嵌入式硬件
无小道2 小时前
c++-引用(包括完美转发,移动构造,万能引用)
c语言·开发语言·汇编·c++
爱莉希雅&&&2 小时前
技术面试题,HR面试题
开发语言·学习·面试
FirstFrost --sy4 小时前
数据结构之二叉树
c语言·数据结构·c++·算法·链表·深度优先·广度优先
Chef_Chen4 小时前
从0开始学习计算机视觉--Day08--卷积神经网络
学习·计算机视觉·cnn
weixin_446260854 小时前
Isaac Lab:让机器人学习更简单的开源框架
学习·机器人
Tanecious.4 小时前
C++--map和set的使用
开发语言·c++