C++反射的实现
来源:互联网 发布:钢铁力量天蝎数据 编辑:程序博客网 时间:2024/05/17 12:54
反射其实就是把创建类的方法和类的字符串名字(当然也可以是相关的信息)绑定起来,这样就可以通过输入的字符串创建对应的类。
闲话少说,上代码:
【基类:Animal】
头文件:
#pragma onceclass Animal{public: Animal(){}; virtual ~Animal(){};public: virtual void test();};typedef Animal* (*funCreateAnimal)();
源文件:
#include "Animal.h"#include <iostream>using namespace std;void Animal::test(){ cout << "Animal" << endl; char ch; cin >> ch;}
【注册用的工厂类:Zoo】
头文件:
#pragma once#include "Animal.h"#include <string>#include <map>using namespace std;// 注册宏#define DECLARE_REGISTER(class_name) \ public: \ static bool s_bRegisterFlag; \ static Animal* CreateInstance() {return new class_name();}#define IMPLEMENT_REGISTER(name, class_name) \ bool class_name::s_bRegisterFlag = \ Zoo::CreateInstance()->RegisterAnimal(name, class_name::CreateInstance);class Zoo{private: map<string, funCreateAnimal>* s_AnimalMap;public: Zoo(){s_AnimalMap = NULL;} ~Zoo(){}public: bool RegisterAnimal(string name, funCreateAnimal fun); Animal* CreateAnimal(string name);public: static Zoo* CreateInstance();};
源文件:
#include "Zoo.h"Zoo* Zoo::CreateInstance(){ static Zoo* instance = new Zoo(); return instance;}bool Zoo::RegisterAnimal(string name, funCreateAnimal fun){ if (s_AnimalMap == NULL) { s_AnimalMap = new map<string, funCreateAnimal>(); } if (name == "") { return false; } if (s_AnimalMap->find(name) == s_AnimalMap->end()) { s_AnimalMap->insert(pair<string, funCreateAnimal>(name, fun)); } return true;}Animal* Zoo::CreateAnimal(string name){ map<string, funCreateAnimal>::const_iterator iter = s_AnimalMap->find(name); if (iter != s_AnimalMap->end()) { funCreateAnimal fun = iter->second; return fun(); } return NULL;}
【子类:Cat】
头文件:
#pragma once#include "Animal.h"#include "Zoo.h"class Cat : public Animal{DECLARE_REGISTER(Cat)public: void test();};
源文件:
#include "Cat.h"#include <iostream>using namespace std;IMPLEMENT_REGISTER("Cat", Cat)void Cat::test(void){ cout << "喵喵~~" << endl; char ch; cin >> ch;}
【测试函数】
#include "Animal.h"#include "Zoo.h"int main(){ Zoo* pZoo = Zoo::CreateInstance(); Animal *animal = NULL; animal = pZoo->CreateAnimal("Cat"); animal->test(); delete animal; animal = NULL; delete pZoo; pZoo = NULL;}
2 0
- Objective-C中关于类反射的实现
- [C#] 反射的用法
- Objective-C的反射
- Objective-C的反射
- Objective-C的反射
- 反射机制的实现
- 实现C++的反射
- Java反射的实现
- 反射的实现原理
- C++反射的实现
- C++反射的实现
- RunTime实现的反射
- C++反射的实现
- C++ 反射的实现
- 安卓so动态库加载代理实现,可以实现C层的类反射效果
- objective c实现配置文件+反射 工厂创建
- c 结构体反射机制实现
- linux下实现C语言反射
- Android开发工具的下载
- 九宫格dfs
- c++ STL学习笔记
- hdu 1058 Humble Numbers
- Redis参数配置说明
- C++反射的实现
- Python smtplib发送邮件 包含文本、附件、图片等
- Android APK免安装启动
- C#中struct的字节对齐、转换操作和复制为二进制数据(byte[])
- 支持向量机(svm)新手入门篇
- 链表中倒数第k个结点
- 创建数据库以及其属性的sql语句
- android socket基于mina框架实现和服务器长连接
- Qt中关于中文字符编码问题