C++ 回调函数的简单例子

调用端

  1. //下面的这个_stdcall很重要的   
  2. void _stdcall Test(int n, string str)   //如果不定义全局变量,而定义在类中 则必须是 静态成员函数  
  3. {  
  4.  while(n-->0)  
  5.   cout<<n<<" "<<str<<endl;  
  6. }  
  7.   
  8.   
  9. int main(int argc, char* argv[])  
  10. {  
  11.  Call call;  
  12.  call.SetFun((MyFun)Test);    //调回调函数的接口,并传入一个函数作为参数  
  13.  call.LetRun(10,"hello");   
  14.    
  15.  printf("Hello World!\n");  
  16.  return 0;  
  17. }  
//下面的这个_stdcall很重要的 
void _stdcall Test(int n, string str)   //如果不定义全局变量,而定义在类中 则必须是 静态成员函数
{
 while(n-->0)
  cout<<n<<" "<<str<<endl;
}


int main(int argc, char* argv[])
{
 Call call;
 call.SetFun((MyFun)Test);    //调回调函数的接口,并传入一个函数作为参数
 call.LetRun(10,"hello"); 
 
 printf("Hello World!\n");
 return 0;
}

 

被调用端

  1. typedef void (_stdcall *MyFun)(int n, string str);  
  2.   
  3. class Call  
  4. {  
  5. private:  
  6.     MyFun myFun;  
  7. public:  
  8.     void SetFun(MyFun _myFun)  
  9.     {  
  10.   myFun = _myFun;       
  11.     }  
  12.       
  13.     void LetRun(int n, string str)                
  14.     {  
  15.   myFun(n, str);       
  16.     }    
  17. };  
typedef void (_stdcall *MyFun)(int n, string str);

class Call
{
private:
    MyFun myFun;
public:
    void SetFun(MyFun _myFun)
    {
  myFun = _myFun;     
    }
    
    void LetRun(int n, string str)              
    {
  myFun(n, str);     
    }  
};


回调过程:调用回调接口【SetFun】  并设置一回调接受函数【Test】  ----->  保存 被调用端传来的 参数 【myFun】-----> 等待.....-----> 

                    LetRun ----->myFun------>回调到Test

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值