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

fibbery 2013-02-28 02:29:14


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;
}



从代码大家应该知道我想干什么,但是,语法有些问题,无法编译通过。大家帮忙调试一下,谢谢!
...全文
128 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
fibbery 2013-02-28
  • 打赏
  • 举报
回复
感谢各位! 另外,虚拟函数可否作为回调函数?
mujiok2003 2013-02-28
  • 打赏
  • 举报
回复

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;
}
lxyppc 2013-02-28
  • 打赏
  • 举报
回复
静态函数相当于就是一个普通函数指针,按照普通函数的方式调用即可 成员函数指针需要用 (a.*fp) 这样的方式来调用
ri_aje 2013-02-28
  • 打赏
  • 举报
回复
是个普通函数指针。

#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;
}
lxyppc 2013-02-28
  • 打赏
  • 举报
回复
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;
}

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧