STL函数对象

一、函数对象

  • 重载函数操作符的类,称为函数对象
  • 函数对象使用重载的()时,行为类似函数调用,也叫做仿函数

本质

函数对象(仿函数)是一个类,不是一个函数。

1.函数对象使用

特点

  • 函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
  • 函数对象超出普通函数的概念,函数对象可以有自己的状态
  • 函数对象可以作为参数传递
#include <iostream>
using namespace std;

class MyAdd
{
    int addNum = 0;//加了几次
public:
    int getNum()
    {
        return addNum;//可以知道返回数据的类型
    }
    int operator()(int v1, int v2)
    {
        addNum++;
        return v1 + v2;
    }
};

void test1()
{
    MyAdd madd;
    cout << madd(12, 12) << endl;
}

int main()
{
    test1();
    system("pause");
}

函数对象作为参数传递

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

class MyPrint
{
public:
    void operator()(const string &mstr,int & i)
    {
        cout << mstr << ":" << i << endl;
    }
};

void doPrint(MyPrint & mp, string test ,int i)
{
    mp(test, i);
}

void test1()
{
    MyPrint mpt;//仿函数使用之前先声明类
    doPrint(mpt,"想你了",19);
}

int main()
{
    test1();
    system("pause");
}
Last modification:May 26th, 2022 at 05:37 pm