什么是函数对象,重载函数调用操作符的类,称其为函数对象。 函数对象使用重载的“()”,行为类似函数调用,也叫仿函数
1.函数对象在使用的时候,可以像普通函数那样调用,可以有参数,有可以有返回值,但本质上并不是一个函数,而是一个对象
//,类名
class MyAdd
{
public :
int operator()(int v1, int v2)
{
return v1 + v2;
}
};
//仿函数使用
void test01()
{
class MyAdd myAdd;
int res = myAdd(1,5);
cout << "res is " << res << endl;
}
2.函数对象超出了普通函数的概念,函数对象可以有自己的状态,这是普通函数不具备的。比如说。
class MyPrint
{
public:
void operator()(string test)
{
cout << test << endl;
this->count++;
}
MyPrint()
{
this->count = 0;
}
int count;
};
void test02()
{
MyPrint myPrint;
myPrint("hello world");
myPrint("hello world");
myPrint("hello world");
myPrint("hello world");
myPrint("hello world");
cout << "myPrint调用次数 "