/*
* C++动态创建对象基本原理
*/
#include <stdio.h>
#include <iostream>
#include <map>
#include <string>
using namespace std;
typedef void* (*pfCreateObject)();
map<string, pfCreateObject> g_Map;
template<typename T>
void* CreatePlugin()
{
return new T;
}
template<typename T>
class PluginRegister
{
public:
PluginRegister(string id)
{
g_Map[id] = CreatePlugin<T>;
}
};
//每个新增加在组件,都应该定义一个全局的注册类对象
class Example1
{
public:
Example1() { cout << "Example1构造函数被调用" << endl; }
};
PluginRegister<Example1> Example1_Register("Example1");
class Example2
{
public:
Example2() { cout << "Example2构造函数被调用" << endl; }
};
PluginRegister<Example2> Example2_Register("Example2");
int main()
{
g_Map["Example1"]();
g_Map["Example2"]();
getchar();
return 0;
}
在VC++和gcc下运行结果相同,输出结果为:
Example1构造函数被调用
Example2构造函数被调用
C++动态对象创建机制
本文介绍了一种在C++中动态创建对象的方法,通过使用模板和全局注册类对象实现。示例展示了如何为不同类注册插件并动态实例化它们,这在插件架构或动态加载模块的场景中非常有用。
1595

被折叠的 条评论
为什么被折叠?



