可打发时间的C语言回调函数理解测试类

李国帅 以前为了加深理解C语言回调写的东西。取自日志。

2011-5-13 8:49:09

关于回调函数,觉得太不可思议了。


#include "stdafx.h"

#include <iostream>
using namespace std;


// 外部的普通函数,接受一个函数指针和一个void指针作为参数
void mfun(void (*pfun)(void *pthis), void *pthis)
{
    (*pfun)(pthis);
}
class test
{
public:
    friend void passfun(void *pthis); //声明一个友元函数
    void func1()
    {
        mfun(passfun, this); //把友元函数的指针和this指针传递给外部函数
    }

private:
    void func2()
    {
        cout<<"test func2."<<endl;
    }
};
void passfun(void *pthis)
{
    ((test*)pthis)->func2(); //在友元函数中调用func2
}
/************************************************************************/
typedef int (*GetInfoFunc)(int nType,char* Info);
class testA
{
public:
    GetInfoFunc m_pInfo;
    void SetCallBackFunc(GetInfoFunc pInfo)
    {
        m_pInfo = pInfo;
    }
    void TestCallBack()
    {
        m_pInfo(1,"dddd");
    }
};

//void forfun(GetInfoFunc GetInfo, void *pthisA)
//{
//    ((testA*)pthisA)->SetCallBackFunc(GetInfo);
//}

class testB
{
public:
    testA m_testA;

    friend int callbackfun(int nType,char* Info);//声明一个友元函数
    void setfunc()
    {
        //forfun(callbackfun,&m_testA); //把友元函数的指针和this指针传递给外部函数
        m_testA.SetCallBackFunc(callbackfun);
    }
};
int callbackfun(int nType,char* Info)
{
    printf(Info);
    return 0;
}

/************************************************************************/

int main()
{
    //test my_test;
    //my_test.func1();

    testB _testB;
    _testB.setfunc();
    _testB.m_testA.TestCallBack();

    cin.get();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lgs790709/article/details/79472741