C++函数调用运算符重载示例

#include <iostream>
#include <stdio.h>
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 test01(){
    MyPrint myprint;
    myprint("helloworld");
}


void test02(){
    // 匿名函数对象调用
    int res = MyAdd()(100, 200);
    printf("%d", res);
}


int main(){
    test01();
    test02();
    return 0;
}

以下为输出结果:

>>> helloworld
>>> 300
posted @ 2021-02-03 10:30  WallEve  阅读(81)  评论(0)    收藏  举报