BZ易风

导航

 

用法一:

#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;  //匿名对象
}

结果:

posted on 2021-08-23 15:01  BZ易风  阅读(65)  评论(0编辑  收藏  举报