c++回調之利用函數指標樣本_C 語言

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.