C++学习之回调函数详解

一、C++中回调函数需要明白两个基础知识:

1、回调函数的设计原理

2、静态成员函数和非静态成员函数区别

二、C++中回调函数使用

在C++中,原则上只能用静态成员函数作为回调函数。因为静态成员函数的地址可用普通函数指针存储,

而普通成员函数地址需要用类成员函数指针来存储。静态成员函数不可以调用类的非静态

成员函数,静态成员函数不含this指针,而普通成员函数默认携带this指针参数。

1、静态成员函数作为回调函数参数,非静态类

静态成员函数作为回调函数参数时,因为静态成员函数没有this指针,所以回调函数

的设计简单,不用包含void*来传递保存this指针

回调函数:

// typedef:常用于定义一个标识符或关键字的别名

// 回调函数指针定义

typedef int (*ptestCB)( stZigBeeMs *);

// 保存回调函数地址

ptestCB m_test;

int  setCBTest(ptestCB pf)

{

    printf(" set cb ok!!!\n");

    m_test = pf;

    return 0;

}

int cbfun()

{

    printf(" cb func !!!\n");

    testMsgType* type = new testMsgType;

    m_test(type);

    return 0;

}

回调函数调用:

Caa.h
class Caa
{
public:
     Caa();
    ~Caa();
    init();
private:
    //设置当前对象为回调函数调用的对象 
    void setCurClass()  
    { 
        spCB = this; 
    }  
    static int onmycb(stZigBeeMsg *  p);
    int dealCB(ptestCB* p);
private:
    static Caa* spCB;//存储回调函数调用的对象
}

Caa* Caa::spCB = NULL;
Caa::Caa()
{
    init();
}
 
Caa::~Caa()
{
}
bool Caa::init()
{
    // 将spCB设置为this供回调使用
    setCurClass();
    // 设置回调函数
    // 需要将成员函数的this指针传入
    // 需要将类成员函数地址强制转换为回调函数类型
    setCBTest(&Caa::onmyevent);
    return true;
}
// 回调函数
int Caa::onmyevent(testMsgType *  p)
{
    // 将回调回来的指针强制转换为类指针,然后调用类的成员函数
    spCB->dealCB(p);
    return 0;
}
// 业务处理函数
int Caa::dealCB(testMsgType* p)
{
    return 0;

猜你喜欢

转载自blog.csdn.net/xueluowutong/article/details/80939363