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

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

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

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

#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;
}

猜你喜欢

转载自www.cnblogs.com/xiximayou/p/12100413.html
今日推荐