C++ Development of Generic Programming Lecture 12 [Function Objects]

One, the concept of function objects

The function object is what we call functor.

The object of the overloaded function operator class is called the function object.

When a function object uses overloaded (), it behaves like a function call.

Nature:

A function object (functor) is an object created by a class, not a function, just like a function.

Second, the use of function objects

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

Example:

#include <string>

//1、函数对象在使用时,可以像普通函数那样调用, 可以有参数,可以有返回值
class MyAdd
{
public :
	int operator()(int v1,int v2)
	{
		return v1 + v2;
	}
};

void test01()
{
	MyAdd myAdd;
	cout << myAdd(10, 10) << endl;
}

//2、函数对象可以有自己的状态
class MyPrint
{
public:
	MyPrint()
	{
		count = 0;
	}
	void operator()(string test)
	{
		cout << test << endl;
		count++; //统计使用次数
	}

	int count; //内部自己的状态
};
void test02()
{
	MyPrint myPrint;
	myPrint("hello world");
	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;
}

to sum up:

The functors are very flexible and can be passed as parameters.

 

Guess you like

Origin blog.csdn.net/Kukeoo/article/details/114106381