C++ 类的成员函数指针 ( function/bind )

这个概念主要用在C++中去实现"委托"的特性. 但现在C++11 中有了 更好用的function/bind 功能.但对于类的成员函数指针的概念我们还是应该掌握的.

 类函数指针 就是要确定由哪个 类的实例 去调用 类函数指针所指的函数.

typedef void (Human::*fp)();  定义了一个类的函数指针.

fp classFunc = &Human::run; // 注意这里是方法的地址.告之具体的指向类中的哪个函数

(human->*p)(); 或 (human.*p)();  // 这是使用一个类的实例去调用类的函数指针 *p 就是取得方法的地址 然后再调用..    

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Human {
 5 public:
 6     virtual void run() = 0;
 7     virtual void eat() = 0;
 8 };
 9 
10 class Mother : public Human {
11 public:
12     void run() {
13         cout << "Mother Run" << endl;
14     }
15     void eat() {
16         cout << "Mother eat" << endl;
17     }
18 };
19 
20 class Father : public Human {
21 public:
22     void run() {
23         cout << "Father run" << endl;
24     }
25     void eat() {
26         cout << "Father eat" << endl;
27     }
28 };
29 
30 typedef void (Human::*fp)();
31 
32 int main() {
33     // 创建一个类的实例
34     Human* human = new Father();
35     // 定义一个类函数指针
36     fp p;
37     // 给类函数指针赋值
38     p = &Human::run;
39     // 调用类的函数指针
40     (human->*p)();
41     return 0;
42 }
原文地址:https://www.cnblogs.com/easyfrog/p/3395429.html