C++成员函数指针

对于类的普通成员函数和静态成员函数,定义函数指针的方法是不同的,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Test {
public:
void func_normal() { //普通成员函数
std::cout << __func__ << std::endl;
}
static void func_static() { //静态成员函数(static)
std::cout << __func__ << std::endl;
}
};

//g++ -std=c++11 to enable std::function
static void foo(std::function<void()> pf)
{
pf();
}

int main(int argc, char* argv[])
{
/* normal function pointer */
void (Test::*pfunc_n)() = NULL;
pfunc_n = &Test::func_normal;
Test t;
(t.*pfunc_n)();
foo(std::bind(&Test::func_normal, &t));

/* static function pointer */
void (*pfunc_s)() = NULL;
pfunc_s = &Test::func_static;
pfunc_s();

return 0;
}

如果一个非静态成员函数指针作为函数参数,则只能把对象传入函数中,然后通过对象调用函数指针。在C++11中引入了function,其本质也是把类传入了函数。