新聞中心
C++編程語言是一款功能強(qiáng)大的計(jì)算機(jī)應(yīng)用語言。其能夠支持很多程序設(shè)計(jì)風(fēng)格。我們今天將會在這里為大家詳細(xì)介紹一下有關(guān)C++反射機(jī)制的具體實(shí)現(xiàn)步驟,大家可以從中獲得一些有幫助的內(nèi)容。

創(chuàng)新互聯(lián)于2013年創(chuàng)立,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目成都網(wǎng)站建設(shè)、成都網(wǎng)站制作網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢想脫穎而出為使命,1280元都江堰做網(wǎng)站,已為上家服務(wù),為都江堰各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:18980820575
在Java編程中,我們經(jīng)常要用到反射,通過反射機(jī)制實(shí)現(xiàn)在配置文件中的靈活配置, 但在C++編程中,對這種方式步提供現(xiàn)有的支持,那么我們怎么才能在配置文件中配置想要調(diào)用的對象呢?
我們的思路是通過對象名稱確定對象實(shí)例,把對象名和對象實(shí)例通過哈希表進(jìn)行映射,那么我們就可以實(shí)現(xiàn)通過對象名稱獲取對象了。首先定義一個(gè)C++反射機(jī)制的結(jié)構(gòu):
- struct ClassInfo
- {
- public:
- string Type;
- funCreateObject Fun;
- ClassInfo(string type, funCreateObject fun)
- {
- Type = type;
- Fun = fun;
- Register(this);
- }
- };
其中Register這樣定義
- bool Register(ClassInfo* ci);
然后定義一個(gè)類,頭文件如下:
- class AFX_EXT_CLASS DynBase
- {
- public:
- DynBase();
- virtual ~DynBase();
- public:
- static bool Register(ClassInfo* classInfo);
- static DynBase* CreateObject(string type);
- private:
- static std::map
m_classInfoMap; - };
cpp文件如下:
- std::map< string,ClassInfo*> DynBase::m_classInfoMap =
std::map< string,ClassInfo*>();- DynBase::DynBase()
- {
- }
- DynBase::~DynBase()
- {
- }
- bool DynBase::Register(ClassInfo* classInfo)
- {
- m_classInfoMap[classInfo->Type] = classInfo;
- return true;
- }
- DynBase* DynBase::CreateObject(string type)
- {
- if ( m_classInfoMap[type] != NULL )
- {
- return m_classInfoMap[type]->Fun();
- }
- return NULL;
- }
那么我們在C++反射機(jī)制的操作中實(shí)現(xiàn)映射的類只要繼承于DynBase就可以了,比如由一個(gè)類CIndustryOperate
頭文件如下
- class CIndustryOperate : public DynBase
- {
- public:
- CIndustryOperate();
- virtual ~CIndustryOperate();
- static DynBase* CreateObject(){return new CIndustryOperate();}
- private:
- static ClassInfo* m_cInfo;
- };
cpp文件如下:
- ClassInfo* CIndustryOperate::m_cInfo = new ClassInfo
("IndustryOperate",(funCreateObject)( CIndustryOperate::
CreateObject));- CIndustryOperate::CIndustryOperate()
- {
- }
- CIndustryOperate::~CIndustryOperate()
- {
- }
以上就是我們?yōu)榇蠹以敿?xì)介紹的C++反射機(jī)制的實(shí)現(xiàn)方法。
網(wǎng)站題目:C++反射機(jī)制具體實(shí)現(xiàn)方法詳解
地址分享:http://www.5511xx.com/article/coigose.html


咨詢
建站咨詢
