仿函数就是可以让类像函数一样使用,因为类的构造函数是不能有返回值的,所以如果你希望调用一个类的对象名+()而有返回值,那就必须要重载()。这样以实现仿函数的功能。实现的代码如下:

#include

using namespace std;

// 自实现求平方类,做成仿函数方式使用
class Pow
{
public:
// 重载()实现仿函数
int operator()(int i)
{
return i * i;
}
// 支持函数重载
double operator()(double d)
{
return d * d;
}
};

int main(int argc, char* argv[])
{
Pow myPow;
// 像函数一样调用
int res = myPow(10);
cout << res << endl;

double dres = myPow(23.4);
cout << dres << endl;

return 0;
}