MFC 类的动态创建(类似于工厂模式)

// DTCJ.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "DTCJ.h"
#include "conio.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// The one and only application object

CWinApp theApp;

using namespace std;

class CAnimal:public CObject{
public:
	DECLARE_DYNCREATE(CAnimal)
	int m_nLeg;
};
IMPLEMENT_DYNCREATE(CAnimal,CObject)

CObject *Factory(CRuntimeClass * pClass){

	return pClass->CreateObject();

}
void Print(){
	CAnimal anil;
	CAnimal *pAnil =new CAnimal();
	//下面这条语句和上面一样 但是下面这条语句更加的灵活很多
	//
	CAnimal *pObj=(CAnimal*)Factory(RUNTIME_CLASS(CAnimal));
	cout<<pObj->m_nLeg<<endl;
	//这就是动态创建
	CWnd *pWnd=(CWnd*)Factory(RUNTIME_CLASS(CWnd));
	cout<<pWnd->m_hWnd<<endl;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	Print();
	getch();
	return 0;
}


你可能感兴趣的:(MFC 类的动态创建(类似于工厂模式))