您的位置:首页 > 其它

对回调函数进行简单封装

2009-05-20 22:30 344 查看
封装的原则很简单,子类通过继承基类的一个虚方法,将回调转到子类的成员函数里面,从而可以使用子类成员函数的一些私有方法和成员。



// ---- code

// .h

#ifndef __KCBBASE_H__
#define __KCBBASE_H__

// -------------------------------------------------------------------------
class KCBBase
{
public:
	static bool CBFunc(void *pData, unsigned int uMsg) 
	{ 
		KCBBase *pThisObject = (KCBBase *) pData ; 
		return pThisObject->Function(uMsg);
	}

    virtual bool Function(unsigned int nMsg){return true;};

protected:
};

class KCBWork : public KCBBase
{
public:
	bool Function(unsigned int nMsg);
	bool SubFunc_1();
	bool SubFunc_2();
	bool SubFunc_3();
};

// 这里使用宏来分发上面的回调,仿造MFC消息分发的方式
#define DECLARE_CBFUN_TABLE() /
	bool Function(unsigned int nMsg); 

#define BEGIN_CBFUN_TABLE(theClass, baseClass)	/
	bool theClass::Function(unsigned int  nMsg)	/
	{							/
		bool bHandle = false;	/
		switch(nMsg)			/
		{

#define ON_CBFUN(nMsg, subFunc) /
		case nMsg:bHandle = subFunc(); break;

#define END_CBFUN_TABLE(theClass, baseClass)			/
		default: bHandle = baseClass::Function(nMsg);	/
		}				/
		return bHandle; /
	}

// 使用宏
class KCBDoWith : public KCBBase
{
public:
	DECLARE_CBFUN_TABLE()
	bool SubFunc_1();
	bool SubFunc_2();
	bool SubFunc_3();
};


// .CPP

#include "stdafx.h"
#include "KCBBase.h"

// -------------------------------------------------------------------------
bool KCBWork::Function(unsigned int nMsg)
{
	bool bRet = false;
	switch(nMsg)
	{
	case 1:
		bRet = SubFunc_1();
		break;
	case 2:
		bRet = SubFunc_2();
		break;
	case 3:
		bRet = SubFunc_3();
	    break;
	default:
		bRet = KCBBase::Function(nMsg);
	    break;
	}

	return bRet;
}

bool KCBWork::SubFunc_1()
{
	return true;
}

bool KCBWork::SubFunc_2()
{
	return true;
}

bool KCBWork::SubFunc_3()
{
	return true;
}

BEGIN_CBFUN_TABLE(KCBDoWith, KCBBase)
	ON_CBFUN(1, SubFunc_1)
	ON_CBFUN(2, SubFunc_2)
	ON_CBFUN(3, SubFunc_3)
END_CBFUN_TABLE(KCBDoWith, KCBBase)

bool KCBDoWith::SubFunc_1()
{
	return true;
}

bool KCBDoWith::SubFunc_2()
{
	return true;
}

bool KCBDoWith::SubFunc_3()
{
	return true;
}


// 使用

KCBDoWith cbDoWith;

KCBDoWith::CBFunc(&cbDoWith, 2);



[END]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: