RUNTIME_CLASS(CAlpha)

By | 2014년 6월 5일
#include "stdafx.h"
#define DEBUG
#define RUNTIME_CLASS(class_name) (&class_name::class##class_name)

class CObject;

//struct CRunTimeClass
struct CRuntimeClass{
    char m_lpszClassName[21];
	int m_nObjectSize;
	CObject* (*pfnCreateObject)(); //함수포인트

	CObject* CreateObject();
};

CObject* CRuntimeClass::CreateObject(){
	return (*pfnCreateObject)();
}

class CObject {
public:
	static CRuntimeClass classCObject;
	virtual CRuntimeClass* GetRuntimeClass()  const { return NULL;}
	virtual ~CObject(){}
protected:
	CObject() {printf("CObject constructor\n");}
};

CRuntimeClass CObject::classCObject={"CObject",sizeof(CObject),NULL};

//class CAlpha
class CAlpha : public CObject
{
public:
	static CRuntimeClass classCAlpha;
	static CObject* CreateObject();
	virtual CRuntimeClass* GetRuntimeClass() const{
		return &classCAlpha;
	}
protected:
	CAlpha() {printf("CAlpha constructor\n");
	};
};

CRuntimeClass CAlpha::classCAlpha={"CAlpha",sizeof(CAlpha),CAlpha::CreateObject};

CObject* CAlpha::CreateObject(){
	return new CAlpha;
}

void main()
{
	//Create CAlpha
	//CRuntimeClass* pRTCAlpha=RUNTIME_CLASS(CAlpha);
	CRuntimeClass* pRTCAlpha=(&CAlpha::classCAlpha);
	CObject* pObj1;

	pObj1=pRTCAlpha->CreateObject();
	//CAlpha의 &OnCreate()가 대입(함수포인터에 의해)
	printf("CAlpha class=%s\n",pObj1->GetRuntimeClass()->m_lpszClassName);

	delete pObj1;

#ifdef DEBUG
	//cmd
	char e;
	scanf("%c",&e);
#endif
}
Category: C++