c++之关系运算符重载

时间:2022-07-23
本文章向大家介绍c++之关系运算符重载,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
#include<iostream>
using namespace std;
class Person {
public:
    Person(string name,int age) {
        m_Name = name;
        m_Age = age;
    }
    string m_Name;
    int m_Age;
    bool operator==(Person& p) {
        if (this->m_Name == p.m_Name && this->m_Age == p.m_Age) {
            return true;
        }
        else
        {
            return false;
        }
    }
    bool operator!=(Person& p) {
        if (this->m_Name == p.m_Name && this->m_Age == p.m_Age) {
            return false;
        }
        else
        {
            return true;
        }

    }
};
void test() {
    Person p1("tom",18);
    Person p2("tomm", 18);
    if (p1 == p2) {
        cout << "p1与p2是相等的" << endl;
    }
    else {
        cout << "p1与p2是不相等的" << endl;
    }
}


int main() {
    test();
    system("pause");
    return 0;
}