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

时间:2022-07-23
本文章向大家介绍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;
}