struct run_time_class; class CObject; typedef run_time_class* p_run_time_class; struct run_time_class { char * m_szClassName; p_run_time_class m_pbaseObj; p_run_time_class m_pNextObj; //uint id; size_t m_objSize; CObject *(*m_pfnCreateObj)(); bool operator == (const run_time_class& _type_info) { return this==&_type_info; } CObject* CreateObject() { if (m_pfnCreateObj) { return (*m_pfnCreateObj)(); } } bool operator != (const run_time_class& _type_info) { return this!=&_type_info; } }; #define DECLEAR_RTTI_SUPPORT(class_name)\ public:\ const static run_time_class class##class_name;\ virtual p_run_time_class GetRunTimeClass()const ;\ static char * GetType();\ static CObject *CreateObject(); #define RETURN_RUNTIME_CLASS(class_name)\ ((run_time_class*)(&class_name::class##class_name)) #define DECLEAR_RTTI_IMPLEMENT_SOME_METHOD(class_name) \ p_run_time_class class_name::GetRunTimeClass()const \ {\ return RETURN_RUNTIME_CLASS(class_name);\ }\ char *class_name::GetType()\ {\ return RETURN_RUNTIME_CLASS(class_name)->m_szClassName;\ }\ CObject* class_name::CreateObject()\ {\ CObject* obj=NULL;\ obj=(CObject*)new class_name;\ return obj;\ } #define DECLEAR_RTTI_IMPLEMENT(class_name_child,class_name_parent)\ const run_time_class class_name_child::class##class_name_child={\ #class_name_child, \ RETURN_RUNTIME_CLASS(class_name_parent),\ NULL,\ sizeof(class_name_child),\ &(class_name_child::CreateObject)\ };\ DECLEAR_RTTI_IMPLEMENT_SOME_METHOD(class_name_child) #define DECLEAR_RTTI_IMPLEMENT_OBJECT(object_name) \ const run_time_class object_name::class##object_name={\ #object_name, \ NULL,\ NULL,\ sizeof(object_name),\ &(object_name::CreateObject)\ };\ DECLEAR_RTTI_IMPLEMENT_SOME_METHOD(object_name) class CObject { public: CObject(){} virtual ~ CObject(){} public: bool IsKindOf(p_run_time_class pObj); virtual void test(){printf("this is a CObject test");} DECLEAR_RTTI_SUPPORT(CObject) }; DECLEAR_RTTI_IMPLEMENT_OBJECT(CObject) bool CObject::IsKindOf(p_run_time_class pObj) { assert(pObj!=nullptr); p_run_time_class pClassThis=GetRunTimeClass(); while(pClassThis!=NULL) { if (pClassThis==pObj) { return true; } pClassThis=pClassThis->m_pbaseObj; } return false; } class A:public CObject { DECLEAR_RTTI_SUPPORT(A) public: A(){} virtual~A(){} public: void test(){printf("this is a test");} }; DECLEAR_RTTI_IMPLEMENT(A,CObject) class test { friend void test_id(); public: virtual ~test(){} test(){} private: test(const test& tst); test& operator =(const test& tst); void printt(){printf("this is a test\n");} public: virtual void a(){} }; class test1:public test { public: test1(){} virtual~test1(){} public : virtual void a(){} }; void test_id() { test a; a.printt(); } int _tmain(int argc, _TCHAR* argv[]) { A a; printf("%d\n",a.IsKindOf(RETURN_RUNTIME_CLASS(CObject))); printf("%s\n",a.GetType()); CObject *run_class=RETURN_RUNTIME_CLASS(A)->CreateObject(); ((A*)(run_class))->test(); ((run_class))->test(); //test_id(); getchar(); return 0; }