Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2647259
  • 博文数量: 416
  • 博客积分: 10220
  • 博客等级: 上将
  • 技术积分: 4193
  • 用 户 组: 普通用户
  • 注册时间: 2006-12-15 09:47
文章分类

全部博文(416)

文章存档

2022年(1)

2021年(1)

2020年(1)

2019年(5)

2018年(7)

2017年(6)

2016年(7)

2015年(11)

2014年(1)

2012年(5)

2011年(7)

2010年(35)

2009年(64)

2008年(48)

2007年(177)

2006年(40)

我的朋友

分类: C/C++

2016-08-05 14:50:02

通过调用者B保留被调用者A的实例指针及静态函数
实现调用者B不关注被调用者A的具体形式及实现
用于c函数调用带有界面类的实现比较方便
c实现中包含了带界面的头文件,往往编译是件头大的事。

#include
using namespace std ;  
//
//class A  
//{  
//public:  
// A(int _p1 = 0, int _p2 = 0):publicValue(_p1), privateValue(_p2){} ;  
// ~A(){} ;  
// void Foo(int value){ 
// cout << value + publicValue << endl ;
// } ;  
//public:  
// int publicValue ;  
//private:  
// int privateValue ;  
//};  
//
//typedef void (A::*FUNCPTR)(int);
//FUNCPTR g_funcF=NULL;
//void setFunc(FUNCPTR _func){
// g_funcF = _func;
//}
//
//void loadFunc(A *a)
//{
// (a->*g_funcF)(1);
//}
//
//int main (int argc, char **argv)  
//{  
// //指向成员变量的指针  
// int A::*pValue = &A::publicValue ;  
// //int A::*pValue = &A::privateValue ; //编译错误,不能是私有成员变量  
//
// //指向成员函数的指针  
// void (A::*pFun)(int) = &A::Foo ;  
//
// A a ;  
// a.*pValue = 20 ;    //对a的publicValue进行赋值  
// (a.*pFun)(10) ;     //调用a的Foo函数
// setFunc(&A::Foo);
// loadFunc(&a);
//}  


#include
using namespace std;
class A
{
public:
A(){
val = 0;
};


static void callback(void *p)  //类的成员函数作为回调函数 static方式实现
{
cout<<"回调函数开始执行了!"< A *a = (A*)p;
a->funB();
}
void funB(){
val++;
cout<<"Fuj="< }


private:
int val;
};


typedef void (*PFunc)(void *);
class B
{
public:
void setFunc(PFunc p, void *pCls)
{
pClass = pCls;
pFunc = p;
}
void trigger(){
pFunc(pClass);
}


private:
void *pClass;
PFunc pFunc;
};


void f(PFunc p, void *pCls)
{
p(pCls);
}


int main()
{
A a;
B b;
PFunc p;
p =A::callback;
f(p, &a);


b.setFunc(p, &a);
b.trigger();
b.trigger();
return 0;
}




阅读(1278) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~