#include<stdlib.h>
#include<iostream>
#include<string>
using namespace std;



/*
    4.5.6 函数调用运算符重载
        函数调用运算符()也可以重载
        由于重载后使用的方式很像函数的调用,故也称为仿函数
        仿函数没有固定写法,很灵活
*/



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



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



void test1(){
    MyPrint mp;
    mp("helloworld"); // 仿函数
    myprint("helloworld"); // 函数调用
}



class MyAdd{
public:
    int operator()(int num1, int num2){
        return num1+num2;
    }
};



void test2(){
    MyAdd ma;
    int sum = ma(10,20);
    cout << sum << endl;

    cout << MyAdd()(100, 100) << endl; // MyAdd()匿名函数对象,(100, 100)仿函数
}



int main()
{
    test1();
    test2();

    system("pause");
    return 0;
}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐