CRuntimeClass::FromName
Call this function to retrieve the CRuntimeClass structure associated with the familiar name.
static CRuntimeClass* PASCAL FromName(
LPCSTR lpszClassName
);
static CRuntimeClass* PASCAL FromName(
LPCWSTR lpszClassName
);
Parameters
lpszClassName
The familiar name of a class derived from CObject.
Return Value
A pointer to a CRuntimeClass object, corresponding to the name as passed in lpszClassName. The function returns NULL if no matching class name was found.
完整代码如下:
#include <iostream>
#include <afxwin.h>
using namespace std;
class CMyClass:
public CObject
{
DECLARE_SERIAL(CMyClass)
};
IMPLEMENT_SERIAL(CMyClass,CObject,1)
//注意,CMyClass必须从CObject派生必须实现了DECLARE_SERIAL, IMPLEMENT_SERIAL两个宏。
class CAge:
public CObject
{
DECLARE_DYNAMIC(CAge)
};
IMPLEMENT_DYNAMIC(CAge,CObject)
int main()
{
// This example creates an object if CMyClass is defined.
CAge * pMyObject=new CAge;
CRuntimeClass* pMyRTClass= pMyObject->GetRuntimeClass();
CRuntimeClass* pClass = pMyRTClass->FromName("CMyClass");
if (pClass == NULL)
{
// not found, display a warning for diagnostic purposes
AfxMessageBox("Warning: CMyClass not defined");
return NULL;
}
// attempt to create the object with the found CRuntimeClass
CObject* pObject = pClass->CreateObject();
cout << pObject->GetRuntimeClass()->m_lpszClassName <<endl;
system("pause");
return 0;
}
代码2:
#include <iostream>
#include <afxwin.h>
using namespace std;
class CMyClass:
public CObject
{
DECLARE_SERIAL(CMyClass)
};
IMPLEMENT_SERIAL(CMyClass,CObject,1)
int main()
{
CObject* pObject = (RUNTIME_CLASS(CObject))->CreateObject("CMyClass");
cout << pObject->GetRuntimeClass()->m_lpszClassName <<endl;
system("pause");
return 0;
}
//代码3
#include <iostream>
#include <afxwin.h>
using namespace std;
class CMyA:public CObject{
DECLARE_DYNCREATE(CMyA);
public:
void show(){
cout << "CMyA::show()" << this->n <<endl;
}
int n;
};
IMPLEMENT_DYNCREATE(CMyA,CObject);
int main(int argc, char* argv[]) {
CObject* a = RUNTIME_CLASS(CMyA)->CreateObject();
CMyA* b = (CMyA*)a;
b->n = 5;
b->show();
return 0;
}
//注意代码1和代码3之间的区别.