Let's take a look at the simplest function:
void foo(int a){ cout << a << endl;}
Its function pointer type is
void (*)(int);
We can use this method as follows:
void (*pFunc)(int) = &foo;pFunc(123);
This is the basic usage of function pointers.
Class member functions
So what are the differences between function pointers for class member functions?
Observe the following classes:
class Foo{public: //void (Foo::*)(int) void foo(int a) { cout << a << endl; } //void (*)(int) static void bar(int a) { cout << a << endl; }};
We try to use:
void (*pFunc)(int) = &Foo::foo;
Compilation error:
Error: cannot convert 'void (FOO: *) (INT) 'to 'void (*) (INT)' in Initialization
From the above compilation error, we can know that the foo function pointer type is definitely not the expected void (*) (INT), but void (FOO: *) (INT ).
The reason is very simple. The class member function contains an implicit parameter this, So Foo actually has two parameters: Foo * and Int.
Then we try to use the void (FOO: *) (INT) type, as follows:
void (Foo::*pFunc2)(int) = &Foo::foo;
So how can we call it? We use the following two methods:
Foo f;(f.*pFunc2)(45678);
And
Foo *pf = &f;(pf->*pFunc2)(7865);
In this case, the usage is correct.
So what are the characteristics of the bar function as a static function?
void (*pFunc)(int) = &Foo::bar; pFunc(123);
We found that the pointer types of static and free functions are the same.
Since Foo contains an implicit parameter, can it be converted? We use mem_fun in STL, which is a function adapter.
Foo f;//void (Foo::*)(int) -> void (*)(Foo*, int)(mem_fun(&Foo::foo))(&f, 123);
We can see that mem_func serves as a conversion function, converting the void (FOO: *) (INT) type member function pointer to void (*) (FOO *, INT ), the latter is a pointer of the free function type and can be freely called.
Complete.
Class member function pointer and mem_fun adapter usage