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

相关推荐
zh_xuan3 小时前
c++ 单例模式
开发语言·c++·单例模式
恰薯条的屑海鸥5 小时前
零基础在实践中学习网络安全-皮卡丘靶场(第十六期-SSRF模块)
数据库·学习·安全·web安全·渗透测试·网络安全学习
利刃大大5 小时前
【在线五子棋对战】二、websocket && 服务器搭建
服务器·c++·websocket·网络协议·项目
喜欢吃燃面5 小时前
C++刷题:日期模拟(1)
c++·学习·算法
SHERlocked935 小时前
CPP 从 0 到 1 完成一个支持 future/promise 的 Windows 异步串口通信库
c++·算法·promise
2301_797604246 小时前
学习记录:DAY32
学习
虚拟之7 小时前
36、stringstream
c++
我很好我还能学7 小时前
【面试篇 9】c++生成可执行文件的四个步骤、悬挂指针、define和const区别、c++定义和声明、将引用作为返回值的好处、类的四个缺省函数
开发语言·c++
蓝婷儿7 小时前
6个月Python学习计划 Day 16 - 面向对象编程(OOP)基础
开发语言·python·学习
叶子2024227 小时前
学习使用YOLO的predict函数使用
人工智能·学习·yolo