首页 > 编程语言 > 详细

c++之函数调用运算符重载

时间:2019-12-26 10:03:36      阅读:89      评论:0      收藏:0      [点我收藏+]

函数调用运用()也可以重载。

由于重载后的使用方法非常像函数的调用,因此称为仿函数。

仿函数没有固定写法,非常灵活。

#include<iostream>
using namespace std;

class MyPrint {
public:
    void operator()(string test) {
        cout << test << endl;
    }
};
class MyAdd {
public:
    int operator()(int num1, int num2) {
        return num1 + num2;
    }
};
void test() {
    MyPrint myPrint;
    MyAdd myAdd;
    myPrint("hello world");
    int res = myAdd(1, 2);
    cout << res << endl;
    //匿名函数对象
    cout << MyAdd()(1, 2) << endl;
}


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

c++之函数调用运算符重载

原文:https://www.cnblogs.com/xiximayou/p/12100413.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!