C++之运算符重载(三)

一.关系运算符重载

//重载关系("==" "!="  ---(< >) 类比--- )运算符
#include <iostream>
#include <string>
using namespace std;

class Person
{
private:
    string m_Name;
    int m_Age;
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;
        }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;
        }
    }
};

int main(){
    Person p1("Tom",1);
    Person p2("Jack",2);

    if(p1 == p2){
        cout<<"true"<<endl;
    }

    if(p1 != p2){
        cout<<"false"<<endl;
    }

    system("pause");
}


二.函数调用运算符重载

//函数调用运算符(())重载
#include <iostream>
#include <string>
using namespace std;


class Print
{
public:
    void operator()(string test){
        cout<<test<<endl;
    }
};

class Add
{
public:
    void operator()(int a , int b){
        cout<<a + b<<endl;
    }
};

void test01(){
    Print t;
    t("hello!");
}

void test02(){
    Add a;
    a(100,100);

    //匿名对象调用    Add()   是一个匿名对象
    Add()(100,100);
}

int main(){
    test01();
    test02();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值