The function object is not a function pointer. However, in program code, it is called like a function pointer, followed by parentheses.
This is the entry-level essay, which is about the definition of a function object, the use of it, and its relationship to function pointers, member function pointers.
Mu Feng Xiao Build
A function object is essentially a class that implements the operator ()-bracket operator.
For example:
class Add
{
public:
int operator()(int a, int b)
{
return a + b;
}
};
Add add; // 定义函数对象
cout << add(3,2); // 5
The function pointer version is:
int AddFunc(int a, int b)
{
return a + b;
}
typedef int (*Add) (int a, int b);
Add add = &AddFunc;
cout << add(3,2); // 5
Oh, in addition to the definition of the same way, the use of the same way. are:
cout << Add (3,2);
Since function objects and function pointers are not different in how they are used, why use a function object? Quite simply, a function object can carry additional data, and the pointer is not.
Here's an example of using additional data:
class less
{
public:
less(int num):n(num){}
bool operator()(int value)
{
return value < n;
}
private:
int n;
};
When in use:
Less isless (10);
cout << isless (9) << "" << isless (12);//Output 1 0
This example seems too trifling to change one:
const int SIZE = 5;
int array[SIZE] = { 50, 30, 9, 7, 20};
// 找到小于数组array中小于10的第一个数的位置
int * pa = std::find_if(array, array + SIZE, less(10)); // pa 指向 9 的位置
// 找到小于数组array中小于40的第一个数的位置
int * pb = std::find_if(array, array + SIZE, less(40)); // pb 指向 30 的位置