编程语言
首页 > 编程语言> > C++仿函数的基本使用

C++仿函数的基本使用

作者:互联网

C++ 提供了仿函数

概念:
  重载函数调用操作符的类,其对象成为函数对象
  函数对象使用重载()时,行为类似函数调用,也叫仿函数
本质:
仿函数是一个类,不是一个函数
特点:
  仿函数在使用时可以像普通函数一样调用
  函数对象不是普通函数,它可以拥有自己的状态,比如统计调用了多少次
  仿函数可以作为形参参数传递(类似函数编程)
分类:
  算术仿函数
  关系仿函数
  逻辑仿函数

基本使用

#include <vector>
#include <string>
#include <iostream>
#include <functional>

using namespace std;

std::function<int (int)> Functional;


int testFunc(int i) {
    return i;
}

auto lambda = [](int i) -> int { return i; };

class Functor {
public:
    int operator()(int i) {
        return i;
    }
};

class test{
public:
    int foo(int i) { return i; }
    static int staticFunc(int i) { return i; }
};

int  main() {
    Functional = testFunc;
    std::cout << "普通函数:" << Functional(1) << std::endl;

    Functional = lambda;
    std::cout << "lambda函数:" << Functional(2) << std::endl;

    Functor functor;
    Functional = functor;
    std::cout << "仿函数:" << Functional(3) << std::endl;

    test ctest;
    Functional = test::staticFunc;
    std::cout << "类静态函数:" << Functional(4) << std::endl;

    Functional = std::bind(&test::foo, ctest, std::placeholders::_1);
    std::cout << "类成员函数:" << Functional(5) << std::endl;

    std::cin.get();
    return 0;
}

标签:基本,std,return,函数,int,C++,函数调用,include
来源: https://www.cnblogs.com/codebai/p/16250340.html