5.1运行时动态识别

_AFX.h

#ifndef _AFX_H_ #define _AFX_H_ #include <windows.h> class CObject; struct CRuntimeClass { LPCSTR m_lpszClassName;//类名称 int m_nObjectSize;//类大小 UINT m_wSchema;//版本号 CObject* (__stdcall* m_pfnCreateObject)();//创建类函数的指针(注意是创建类,而不是创建对象啊) CRuntimeClass* m_pBaseClass;//其基类的地址 CObject* CreateObject(); BOOL IsDerivedFrom(const CRuntimeClass* pBaseClass) const; CRuntimeClass* m_pNextClass; }; class CObject { public: virtual CRuntimeClass* GetRuntimeClass() const; virtual ~CObject(); BOOL IsKindOf(const CRuntimeClass* pClass) const; static const CRuntimeClass classCObject; protected: private: }; inline CObject::~CObject() {} #define RUNTIME_CLASS(class_name) ((CRuntimeClass*)&class_name::class##class_name) //CRuntimeClass命名规则:在类名前冠以class作为名字,##是告诉编译器,把两个字符串捆绑在一起 #define DECLARE_DYNAMIC(class_name)/ public:/ static const CRuntimeClass class##class_name;/ virtual CRuntimeClass* GetRuntimeClass() const; #define IMPLEMENT_RUNTIMECLASS(class_name,base_class_name,wSchema,pfnNew)/ const CRuntimeClass class_name::class##class_name = {/ #class_name,sizeof(class class_name),wSchema,pfnNew,/ RUNTIME_CLASS(base_class_name),NULL};/ CRuntimeClass* class_name::GetRuntimeClass() const/ {/ return RUNTIME_CLASS(class_name);/ }/ //宏写的没什么意思 #endif//_AFX_H_

OBJCORE.cpp

#include "_AFX.H" const struct CRuntimeClass CObject::classCObject = { "CObject",//类名 sizeof(CObject),//大小 0xffff,//无版本号 NULL,//不支持动态创建 NULL,//没有基类 NULL }; CRuntimeClass* CObject::GetRuntimeClass() const{ return RUNTIME_CLASS(CObject);//这是那个宏,返回动态运行类的名称吧 } BOOL CObject::IsKindOf(const CRuntimeClass* pClass) const{ CRuntimeClass* pClassThis = GetRuntimeClass(); return pClassThis->IsDerivedFrom(pClass); }

TypeIdentify.cpp

#include "_AFX.H" #include <iostream> using namespace std; class CPerson:public CObject{ public: virtual CRuntimeClass* GetRuntimeClass() const{ return (CRuntimeClass*)&classCPerson; } static const CRuntimeClass classCPerson; static CObject* __stdcall CreateObject(){ // 这样的话支持运行时动态创建 return new CPerson; } }; const CRuntimeClass CPerson::classCPerson = { "CPerson", sizeof(CPerson), 0xffff, &CPerson::CreateObject,//添加的时候不要加() (CRuntimeClass*)&CObject::classCObject,//这个是他的基类 NULL }; int mian(){ CRuntimeClass* pRuntimeClass = RUNTIME_CLASS(CPerson); CObject *pObject = pRuntimeClass->CreateObject(); delete pObject; CObject* pMyObject = new CPerson;//看到了c++的强大之处,这是其一 if (pMyObject->IsKindOf(RUNTIME_CLASS(CPerson))) { CPerson* pMyPerson = (CPerson*)pMyObject; cout << "a CPerson created!/n"; delete pMyPerson; } else { delete pMyObject; } return 0; }

就学了一个运行时的动态创建,不知道具体有什么作用,哎,明天继续往下看。

自己的思考都在注释里了,但是有两个宏没写完,没什么太大的意义,只是简化使用而已,宏的写法居然没看懂,看来还是有必要加强。

你可能感兴趣的:(5.1运行时动态识别)