首页 > 代码库 > 类非静态成员的函数指针 的使用 Function pointer of a non-static member function of a class

类非静态成员的函数指针 的使用 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() {}
};

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