c++函数指针 c++回调之利用函数指针示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

c++函数指针 c++回调之利用函数指针示例

  2021-03-19 我要评论
想了解c++回调之利用函数指针示例的相关内容吗,在本文为您仔细讲解c++函数指针的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:c++,函数指针,下面大家一起来学习吧。

c++回调之利用函数指针示例

复制代码 代码如下:

#include <iostream>
using namespace std;


/************************************************************************/
/*                下层实现: CALLBACK                                        */
/************************************************************************/

typedef void (*CALLBACKFUN)(int a,int b);

class base
{
private:
    int m;
    int n;
    static CALLBACKFUN pfunc;
public:
    base():m(0), n(0){};
    void registercallback(CALLBACKFUN fun,int k,int j);
    void callcallback();
};

CALLBACKFUN base::pfunc=NULL;    /* static初始化 */

// 注册回调函数
void base::registercallback(CALLBACKFUN fun,int k,int j)
{
    pfunc=fun;
    m=k;
    n=j;
}

void base::callcallback()
{
    base::pfunc(m,n);
}

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

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

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

复制代码 代码如下:

// cbByfunction.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "cbByfunction.h"

/************************************************************************/
/*                    上层回调注册                                        */
/************************************************************************/
void seiya(int a,int b)
{
    cout << "..." << a << "..." << b << endl;
    cout << "this is seiya callback function" <<endl;
}

void zilong(int a,int b)
{
    cout<<a<<endl<<b<<endl;
    cout<<"this is zilong callback function"<<endl;
}

int main(int argc, char* argv[])
{
    // 注册下层回调函数
    base c_base;
    c_base.registercallback(seiya, 5, 6);
    c_base.callcallback();
    c_base.registercallback(zilong, 7, 8);
    c_base.callcallback();
    return 0;
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们