关系运算符重载

关系运算符重载

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

代码示例:

#include <iostream>
#include <string>
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;
       }
       bool operator!=(Person &p)
       {
   
              if (this->m_Name == p.m_Name&&this->m_Age == p.m_Age)
              {
   
                     return false;
              }
              return true;
       }
       string m_Name;
       int m_Age;
};
void test01()
{
   
       Person p1("Tom", 18);
       Person p2("Jerry", 18);
       if (p1 == p2)
       {
   
              cout << "p1和p2是相等的! " << endl;
       }
       else
       {
   
              cout<< "p1和p2是不相等的! " << endl;
       }
       if (p1 != p2)
       {
   
              cout << "p1和p2是不相等的! " << endl;
       }
       else
       {
   
              cout << "p1和p2是相等的! " << endl;
       }
}
int main()
{
   
       test01();
       return 0;
}

感兴趣欢迎关注微信公众号黑马金牌编程,该公众号专注于后端开发领域

C/C++基础 文章被收录于专栏

本专栏收录C/C++编程语言相关知识

全部评论

相关推荐

CARLJOSEPH...:宝宝你戾气太大了
点赞 评论 收藏
分享
06-17 21:57
门头沟学院 Java
白友:噗嗤,我发现有些人事就爱发这些,明明已读不回就行了,就是要恶心人
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务