非静态成员函数回调的有关问题

非静态成员函数回调的问题。


class CTest
{
public:
   static int callback(CTest * pThis)
   {
      std::cout<<"run"<<std::endl;
      return 0;
   }
};

typedef int (CTest::*FUNC)(CTest *);

int main()
{
   CTest a;
   FUNC fp=CTest::callback;
   (a.*fp)(&a);
   return 0;
}



从代码大家应该知道我想干什么,但是,语法有些问题,无法编译通过。大家帮忙调试一下,谢谢!

------解决方案--------------------

class CTest
{
public:
   static int callback(CTest * pThis)
   {
      std::cout<<"run"<<std::endl;
      return 0;
   }
   int callback2(){ callback(this); }
};

typedef int (CTest::*FUNC)();
typedef int (*FUNC2)(CTest *);
int main()
{
   CTest a;
   FUNC fp= &CTest::callback2;
   FUNC2 fp2= CTest::callback;
   (a.*fp)();
   fp2(&a);
   return 0;
}

------解决方案--------------------
是个普通函数指针。

#include <iostream>
using namespace std;

class CTest
{
public:
 static int callback(CTest * pThis)
 {
  std::cout<<"run"<<std::endl;
  return 0;
 }
};

typedef int (*FUNC)(CTest *);

int main()
{
 CTest a;
 FUNC fp=&CTest::callback;
 fp(&a);
 return 0;
}

------解决方案--------------------
静态函数相当于就是一个普通函数指针,按照普通函数的方式调用即可
成员函数指针需要用 (a.*fp) 这样的方式来调用
------解决方案--------------------

class CTest
{
public:
int another()
{
//
return 0;
}
   static int callback(CTest * pThis)
   {
      //std::cout<<"run"<<std::endl;
      return 0;
   }
};

int main()
{
   CTest a;
   //non-member functon version
   int (*cb)(CTest*) = &CTest::callback;
   (*cb)(&a);
   //member fuction version
   int (CTest::*cb2)() = &CTest::another;
   (a.*cb2)();
   return 0;
}