11.5.5重学C++之【关系运算符重载】

#include<stdlib.h>
#include<iostream>
#include<string>
using namespace std;



/*
    4.5.5 关系运算符重载
        可以让连个自定义类型的对象进行对比操作
*/



class Person{
public:
    string name;
    int age;

public:
    Person(string _name, int _age){
        name = _name;
        age = _age;
    }

    // 重载==
    bool operator==(Person & p){
        if(this->name==p.name && this->age==p.age){
            return true;
        }
        return false;
    }
    // 重载!=
    bool operator!=(Person & p){
        if(this->name!=p.name || this->age!=p.age){
            return true;
        }
        return false;
    }
};



void test1(){
    Person p1("tom", 18);
    Person p2("tom", 20);

    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()
{
    test1();

    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/HAIFEI666/article/details/114896695
今日推荐