zoukankan      html  css  js  c++  java
  • C++回调:利用函数指针

     1 #include <iostream>
     2 using namespace std;
     3 
     4 
     5 /************************************************************************/
     6 /*                下层实现: CALLBACK                                        */
     7 /************************************************************************/
     8 
     9 typedef void (*CALLBACKFUN)(int a,int b);
    10 
    11 class base
    12 {
    13 private:
    14     int m;
    15     int n;
    16     static CALLBACKFUN pfunc;
    17 public:
    18     base():m(0), n(0){};
    19     void registercallback(CALLBACKFUN fun,int k,int j);
    20     void callcallback();
    21 };
    22 
    23 CALLBACKFUN base::pfunc=NULL;    /* static初始化 */
    24 
    25 // 注册回调函数
    26 void base::registercallback(CALLBACKFUN fun,int k,int j)
    27 {
    28     pfunc=fun;
    29     m=k;
    30     n=j;
    31 }
    32 
    33 void base::callcallback()
    34 {
    35     base::pfunc(m,n);
    36 }

    下层定义回调函数的时候,需要提供以下几个接口:

    1. 实现注册接口:提供一个接口给上层,通过该接口,上层注册回调实现接口,下层将该实现接口地址传递给定义的回调指针(CALLBACKFUN),该初始化动作是必须的,否则无法实现回调;

    2. 触发接口:该接口提供触发行为,当调用该接口时,就会触发一次函数回调;

     1 // cbByfunction.cpp : Defines the entry point for the console application.
     2 //
     3 
     4 #include "stdafx.h"
     5 #include "cbByfunction.h"
     6 
     7 /************************************************************************/
     8 /*                    上层回调注册                                        */
     9 /************************************************************************/
    10 void seiya(int a,int b)
    11 {
    12     cout << "..." << a << "..." << b << endl;
    13     cout << "this is seiya callback function" <<endl;
    14 }
    15 
    16 void zilong(int a,int b)
    17 {
    18     cout<<a<<endl<<b<<endl;
    19     cout<<"this is zilong callback function"<<endl;
    20 }
    21 
    22 int main(int argc, char* argv[])
    23 {
    24     // 注册下层回调函数
    25     base c_base;
    26     c_base.registercallback(seiya, 5, 6);
    27     c_base.callcallback();
    28     c_base.registercallback(zilong, 7, 8);
    29     c_base.callcallback();
    30     return 0;
    31 }
  • 相关阅读:
    为什么重写equals还要重写hashcode?
    谈谈关于Synchronized和lock
    springBoot为啥没有没有web.xml了
    springBoot整合mybatis开发
    springBoot的介绍与搭建
    Java i++原理及i=i++的问题说明
    Django学习笔记〇三——APP以及的文件结构
    Django学习笔记〇二——第一个Django项目
    Django学习笔记〇一——从web的概念引入
    MySQL学习笔记——〇六SQLAlchemy框架
  • 原文地址:https://www.cnblogs.com/davidsguo008/p/3637796.html
Copyright © 2011-2022 走看看