C++基础--回调的应用

一、类成员函数的回调

1. 类成员函数的回调,函数的调用必须通过类来调用;

CallBack.h

#pragma once

class CallBack
{
public:
    CallBack();
    ~CallBack();
    typedef void (CallBack::*pFunc)(int);
    void printFunc(int x);
    void FuncCall(CallBack *obj, CallBack::pFunc p);
};

 CallBack.cpp

#include "CallBack.h"
#include <stdio.h>

CallBack::CallBack()
{
}

CallBack::~CallBack()
{
}

void CallBack::printFunc(int x)
{
    printf("CALLBACK x value is %d\n", x);
}

void CallBack::FuncCall(CallBack *obj, CallBack::pFunc p)
{
    int x = 5;
    (obj->*p)(x);
}

main.cpp

#include "CallBack.h"

int main()
{
    CallBack *cb = new CallBack();
    cb->FuncCall(cb, &CallBack::printFunc);
    
    return 0;
}

运行结果为:

 二、静态函数的回调

注意:1. 静态函数只能在声明这个函数的文件中调用;

CallBack.h

#pragma once

typedef void(*pFunc)(int);
static void printFunc(int x);
void FuncCall(pFunc p, int x);
void excute(int x);

CallBack.cpp

#include "CallBack.h"
#include <stdio.h>

static void printFunc(int x)
{
    printf("CALLBACK x value is %d\n", x);
}

void FuncCall(pFunc p, int x)
{
    (*p)(x);
}

void excute(int x)
{
    FuncCall(printFunc, x);
}

main.cpp

#include "CallBack.h"

int main()
{
    int x = 5;
    excute(x);
    return 0;
}

运行结果为:

 三、回调函数在继承里的应用

Base.h

#pragma once
class CBase
{
public:
    CBase();
    virtual ~CBase();

    char* x;
    typedef void (CBase::*pFunc)();
    virtual void printX();
    void FuncCall(CBase* bs, pFunc p);
};

Base.cpp

#include "Base.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

CBase::CBase()
{
    x = NULL;
    x = (char*)calloc(1, 256);
    strcpy_s(x, 256, "Base X\n");
}

CBase::~CBase()
{
}

void CBase::printX()
{
    printf_s("BASE %s", x);
}

void CBase::FuncCall(CBase *obj, CBase::pFunc p)
{
    (obj->*p)();
}

CallBack.h

#pragma once
#include "Base.h"

class CallBack:public CBase
{
public:
    CallBack();
    ~CallBack();

    virtual void printX();
};

CallBack.cpp

#include "CallBack.h"
#include <stdio.h>
#include <string.h>

CallBack::CallBack()
{
}

CallBack::~CallBack()
{
}

void CallBack::printX()
{
    strcpy_s(x, 256, "EXTERN x");
    printf_s("EXTERN %s", x);
}

main.cpp

#include "CallBack.h"
#include "Base.h"

int main()
{
    CBase *b = new CallBack();
    b->FuncCall(b, &CBase::printX);
    return 0;
}

运行结果:

 

posted on 2018-06-06 17:42  Anlia  阅读(178)  评论(0编辑  收藏  举报

导航