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

本文通过一个C++示例程序介绍了如何使用动态创建技术来实例化对象,并演示了如何利用运行时类信息来创建不同类型的对象。文章还展示了如何为不同类型的对象调用成员变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值