用统一的一个结构管理动态创建
#define RUN_TIME(classname) (&classname::runtime)
#define DECLARE_DYNAMIC()\ public:\ static RUNTIME runtime;\ virtual char *GetClassName();\ virtual char *GetBaseClassName();\ static CObject *MyCreate();
#define IMPLEMENT_DYNAMIC(theclass, baseclass)\ RUNTIME theclass::runtime = {#theclass, &baseclass::runtime, theclass::MyCreate};\ char *theclass::GetClassName()\ {\ return theclass::runtime.classname;\ }\ char *theclass::GetBaseClassName()\ {\ return theclass::runtime.Baseruntime->classname;\ }\ CObject * theclass::MyCreate()\ {\ return new theclass;\ }
typedef struct _RUNTIME { char *classname; struct _RUNTIME *Baseruntime; CObject *(*pfnCreate)(); CObject *Create(); }RUNTIME; CObject * _RUNTIME::Create() { return new CObject; }
宏替换:在预编译阶段,对我们源程序文本进行处理。动态创建机制,实际是一种预编译替换机制
编译阶段:我们的源程序将不再发生任何改变。