天下

记录修行的印记

在VC2005中,只要知道类的名字,就可以动态创建类的实例

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-><<endl;
    }
    
int n;
};
IMPLEMENT_DYNCREATE(CMyA,CObject);


int main(int argc, char* argv[]) {
    CObject
* a = RUNTIME_CLASS(CMyA)->CreateObject();
    CMyA
* b = (CMyA*)a;
    b
->= 5;
    b
->show();
    
return 0;
}

//注意代码1和代码3之间的区别.

posted on 2010-10-26 17:04 天下 阅读(514) 评论(1)  编辑 收藏 引用

评论

# shi 2010-12-22 09:29 uk dress

good post...I like this very much...  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2010年10月>
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456

导航

统计

常用链接

留言簿(4)

随笔分类(378)

随笔档案(329)

链接

最新随笔

搜索

最新评论