C++重载(一):关系符重载

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

#include<iostream>
#include<string>
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;
        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;
    }

    string m_Name;
    int m_Age;
};

void test01()
{
    
    
    Person a("DYF", 25);
    Person b("DYF", 25);

    if(a==b)
        cout << "a==b is true" << endl;
    else
        cout << "a==b is false" << endl;

    if(a!=b)
        cout << "a!=b is true" << endl;
    else
        cout << "a!=b is false" << endl;
}

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

猜你喜欢

转载自blog.csdn.net/weixin_40437821/article/details/113482592
今日推荐