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

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() {}
};
posted @ 2017-03-02 11:43  穆穆兔兔  阅读(310)  评论(0编辑  收藏  举报