仿函数 也叫 函数对象;
《C++标准程序库》里对仿函数的解释是:仿函数是泛型编程强大威力和纯粹抽象概念的又一例证。
你可以说,任何东西,只要其行为像函数,它就是一个函数。
因此如果你定义了一个对象,行为像函数,它就可以被当做函数来用。
那么,什么才算具备函数行为呢?
所谓函数行为,是指可以 “使用小括号 () 传递参数,籍以调用某个东西”。
#include <iostream>
using namespace std;
class MyPrint
{
public:
void operator()( string a ) // 函数调用运算符重载
{
cout << a << endl;
}
};
void RealPrintFun( string b)
{
cout << b << endl;
}
int main()
{
// 使用方法类似函数调用,因此称为 “仿函数”
MyPrint fakeprintfun;
fakeprintfun("fakeprintfun: Hello World");
// 匿名对象调用,不创建专门的对象来调用
MyPrint()("anonymous object MyPrint(): Hello World");
// 真正的函数调用
RealPrintFun("RealPrintFun: Hello World");
return 0;
}
输出结果:
fakeprintfun: Hello World
anonymous object MyPrint(): Hello World
RealPrintFun: Hello World