运算符重载——函数调用运算符重载

函数调用运算符重载:
  • 本质上就是重载双括号()
  • 重载后的函数称为仿函数
  • 仿函数没有固定写法,非常灵活

代码:

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

    void operator()(int i) {
        cout << i << endl;
    }

};

class MyAdd {
public:
    int operator()(int a, int b) {
        return a + b;
    }
};

int main() {
    string s = "hello";

    MyPrint myPrint;
    MyAdd myAdd;

    myPrint(s);// 打印hello
    myPrint(myAdd(1,1));// 打印2

    //使用匿名对象来调用
    myPrint(MyAdd()(1,3));// 打印4

    return 0;
}

核心代码:

    void operator()(string test) {
        cout << test << endl;
    }

    void operator()(int i) {
        cout << i << endl;
    }
    
    int operator()(int a, int b) {
        return a + b;
    }

需要注意的点:

  • 调用仿函数的方式:对象名(传入相应参数);
  • 也可以用匿名对象来调用:类名()(传入相应参数);

匿名对象的特点是执行完改行代码后立刻调用析构函数,释放对象空间,不再是执行完main方法后再调用对象的析构函数.

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值