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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值