您的位置:首页 > 健康 > 养生 > C++基础知识:关系运算符重载以及相关代码演示

C++基础知识:关系运算符重载以及相关代码演示

2024/10/6 12:28:50 来源:https://blog.csdn.net/zxn275266/article/details/141727830  浏览:    关键词:C++基础知识:关系运算符重载以及相关代码演示

1.作用:

重载关系运算符,可以让两个自定义类型对象进行对比操作

2.代码:


#include<iostream>
using namespace std;//重载关系运算符class Person {
public:Person(string name, int age) {m_Name = name;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("Joy", 18);if (p1 == p2) {cout << "p1和p2是相等的!" << endl;}else {cout << "p1和p2是不相等的!" << endl;}
}int main() {test01();system("pause");return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com