welkinzz

C++反射机制具体实现方法详解(转帖:原作者不详)

C++编程语言是一款功能强大的计算机应用语言。其能够支持很多程序设计风格。我们今天将会在这里为大家详细介绍一下有关C++反射机制的具体实现步骤,大家可以从中获得一些有帮助的内容。

在Java编程中,我们经常要用到反射,通过反射机制实现在配置文件中的灵活配置, 但在C++编程中,对这种方式步提供现有的支持,那么我们怎么才能在配置文件中配置想要调用的对象呢? 

我们的思路是通过对象名称确定对象实例,把对象名和对象实例通过哈希表进行映射,那么我们就可以实现通过对象名称获取对象了。首先定义一个C++反射机制的结构:

  1. struct ClassInfo  
  2. {  
  3. public:  
  4. string Type;  
  5. funCreateObject Fun;  
  6. ClassInfo(string type, funCreateObject fun)  
  7. {  
  8. Type = type;  
  9. Fun = fun;  
  10. Register(this);  
  11. }  
  12. }; 

其中Register这样定义

  1. bool Register(ClassInfo* ci); 

然后定义一个类,头文件如下:

  1. class AFX_EXT_CLASS DynBase   
  2. {  
  3. public:  
  4. DynBase();  
  5. virtual ~DynBase();  
  6. public:   
  7. static bool Register(ClassInfo* classInfo);  
  8. static DynBase* CreateObject(string type);  
  9. private:   
  10. static std::map<string,ClassInfo*> m_classInfoMap;  
  11. }; 

cpp文件如下:

  1. std::map< string,ClassInfo*> DynBase::m_classInfoMap = 
    std::map< string,ClassInfo*>();  
  2. DynBase::DynBase()  
  3. {  
  4. }  
  5. DynBase::~DynBase()  
  6. {  
  7. }  
  8. bool DynBase::Register(ClassInfo* classInfo)  
  9. {   
  10. m_classInfoMap[classInfo->Type] = classInfo;   
  11. return true;   
  12. }  
  13. DynBase* DynBase::CreateObject(string type)  
  14. {  
  15. if ( m_classInfoMap[type] != NULL )   
  16. {   
  17. return m_classInfoMap[type]->Fun();  
  18. }  
  19. return NULL;  

那么我们在C++反射机制的操作中实现映射的类只要继承于DynBase就可以了,比如由一个类CIndustryOperate

头文件如下

  1. class CIndustryOperate : public DynBase  
  2. {  
  3. public:  
  4. CIndustryOperate();  
  5. virtual ~CIndustryOperate();  
  6. static DynBase* CreateObject(){return new CIndustryOperate();}  
  7. private:  
  8. static ClassInfo* m_cInfo;  
  9. }; 

cpp文件如下:

  1. ClassInfo* CIndustryOperate::m_cInfo = new ClassInfo
    ("IndustryOperate",(funCreateObject)( CIndustryOperate::
    CreateObject));  
  2. CIndustryOperate::CIndustryOperate()  
  3. {  
  4. }  
  5. CIndustryOperate::~CIndustryOperate()  
  6. {  

以上就是我们为大家详细介绍的C++反射机制的实现方法。

posted on 2011-04-19 01:25  照世明灯  阅读(495)  评论(0编辑  收藏  举报

导航