码迷,mamicode.com
首页 > 其他好文 > 详细

类非静态成员的函数指针 的使用 Function pointer of a non-static member function of a class

时间:2017-03-02 12:23:40      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:stat   str   lib   int   ted   single   ptr   pointer   led   

you can get the pointer of the method, but it has to be called with an object

typedef void (T::*MethodPtr) ();
MethodPtr method = &T::MethodA;
T *obj = new T();
obj->*method();

If you need to have non-object pointer and you want to use object then you have to store instance of object somewhere, but you are restricted to use only one object (singleton).

class T {
  static T *instance;
public:
  T::T() {
    instance = this;
  }
  static void func() {
    instance->doStuff();
  }
  void doStuff() {}
};

If library supports user data for function pointers, then you may have multiple instances

class T {
public:
  static void func(void *instance) {
    ((T*)instance)->doStuff();
  }
  void doStuff() {}
};

类非静态成员的函数指针 的使用 Function pointer of a non-static member function of a class

标签:stat   str   lib   int   ted   single   ptr   pointer   led   

原文地址:http://www.cnblogs.com/diegodu/p/6489788.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!