Dynamic Creation(动态创建)

DECLARE_DYNCREATE/IMPLEMENT_DYNCREATE宏

用于对象的动态创建,即从保存的文件中恢复原始对象。这2个宏在RTTI即DECLARE_DYNMICAL/IMPLEMENT_DYNAMIC宏的基础上添加了2个成员:

CObject* CreateObject();

static CRuntimeClass* PASCAL Load(CArchive& ar, UINT* pwSchemaNum);//static成员函数,属于类。

 

#define DECLARE_DYNCREATE(class_name) \
 DECLARE_DYNAMIC(class_name) \
 static CObject* PASCAL CreateObject();

 

#define IMPLEMENT_DYNCREATE(class_name, base_class_name) \
 CObject* PASCAL class_name::CreateObject() \
  { return new class_name; } \
 IMPLEMENT_RUNTIMECLASS(class_name, base_class_name, 0xFFFF, \
  class_name::CreateObject, NULL)

 

#define IMPLEMENT_RUNTIMECLASS(class_name, base_class_name, wSchema, pfnNew, class_init) \
 AFX_COMDAT const CRuntimeClass class_name::class##class_name = { \
  #class_name, sizeof(class class_name), wSchema, pfnNew, \
   RUNTIME_CLASS(base_class_name), NULL, class_init }; \
 CRuntimeClass* class_name::GetRuntimeClass() const \
  { return RUNTIME_CLASS(class_name); } \

 

#define AFX_COMDAT __declspec(selectany)

#define RUNTIME_CLASS(class_name) _RUNTIME_CLASS(class_name)

#define _RUNTIME_CLASS(class_name) ((CRuntimeClass*)(&class_name::class##class_name))

Dynamic Creation(动态创建)_第1张图片

CreateObject函数生成对象,若为抽象类,则返回NULL,否则new一个对象

Dynamic Creation(动态创建)_第2张图片

如下是使用:

void main()

{

  ...

  //Test Dynamic Creation

  CRuntimeClass* pClassRef;

  CObject* pOb;

  while(1)

  {

    if((pClassRef = CRuntimeClass::Load())==NULL)

      break;

    pOb = pClassRef->CreateObject();

    if(pOb != NULL)

      pOb->SayHello();

  }

}

 

CObject* CRuntimeClass::CreateObject()

{

  if(m_pfnCreateObject == NULL)

  {

    ...

  }

  CObject* pObject = NULL;

  pObject = (*m_pfnCreateObject)();

  return pOjbect;

}

 

CRuntimeClass* PASCAL CRuntimeClass::Load()

{

  char szClassName[64];

  CRuntimeClass* pClass;

  cout << "enter a class name: ";

  cin >> szClassName;

  for(pClass = pFirstClass; pClass != NULL; pClass = pClass->m_pNextClass)

  {

    if(strcmp(szClassName,pClass->m_lpszClassName) == 0)

      return pClass;

  }

  ...

}

你可能感兴趣的:(dynamic)