用法一:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;

class myPrint
{
public:
    //()重载
    void operator()(string text)
    {
        cout << text << endl;
    }
};

void test01()
{
    myPrint mp;
    mp("Hello World!");   //仿函数
    //仿函数不是一个函数,但是它的行为像是函数的调用
}
int main()
{
    test01();
    system("Pause");
    return 0;
}

结果:

函数调用运算符()重载及仿函数概念

用法二:

class MyAdd
{
public:
    int operator()(int a, int b)
    {
        return a + b;
    }
};
void test02()
{
    MyAdd myAdd;
    cout << myAdd(1, 2) << endl;
}

结果:

函数调用运算符()重载及仿函数概念

 

用法三:匿名对象

class MyAdd
{
public:
    int operator()(int a, int b)
    {
        return a + b;
    }
};
void test02()
{
    cout << MyAdd()(1, 2) << endl;  //匿名对象
}

结果:

函数调用运算符()重载及仿函数概念

相关文章: