STL-Function Object
4.1 Function Object
4.1.1 Concept of Function Object
The class of overloaded function call operator, whose object is often called function object
When the function object uses overloaded (), the behavior is similar to a function call, also called a functor
Essence: a
function object (functor) is a class, not a function.
Function objects are used
Features: When a
function object is in use, it can be called like a normal function, can have parameters, and can have return values
Function object is beyond the concept of ordinary function, function object can have its own state
Function objects can be passed as parameters
Code example:
#include<iostream>
#include<string>
using namespace std;
//函数对象(仿函数)
class MyAdd
{
public:
int operator()(int v1, int v2)
{
return v1 + v2;
}
};
//1.函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
void test01()
{
MyAdd myAdd;
cout << myAdd(10, 10) << endl;
}
//2.函数对象超出普通函数概念,函数对象可以有自己的状态
class Myprint
{
public:
Myprint()
{
this->count = 0;
}
void operator()(string test)
{
cout << test << endl;
this->count++;
}
int count; //内部自己状态
};
void test02()
{
Myprint myPrint;
myPrint("Hello world");
myPrint("Hello world");
cout << "myPrint调用次数为:" << myPrint.count << endl;
}
//3.函数对象可以作为参数传递
void doPrint(Myprint &mp, string test)
{
mp(test);
}
void test03()
{
Myprint myPrint;
doPrint(myPrint, "Hello C++");
}
int main()
{
test01();
test02();
test03();
system("pause");
return 0;
}