Functor 对象模拟函数
把类对象,像函数名一样使用。
仿函数(functor),就是使一个类的使用看上去像一个函数。其实现就是类中实现
一个 operator(),这个类就有了类似函数的行为,就是一个仿函数类了。
operator() 语法格式
class 类名
{
返值类型 operator()(参数类型)
函数体
}
#include <iostream>
#include <math.h>
using namespace std;
class Pow
{
public:
//仿函数
double operator()(double a, int b){
double result = 1;
for(int i=0;i<b;i++){
result *= a;
}
return result;
}
};
int main()
{
cout<<pow(5,2)<<endl;
Pow mypow;
cout<<mypow(5,2)<<endl;
return 0;
}
functor 的优势
functor 的优势在于,是对象形式,可以携带更多的的信息,用于作出判断。
比如,我们可以在对象初始化