【发布时间】:2012-01-06 08:31:19
【问题描述】:
可能重复:
Is there a way to instantiate objects from a string holding their class name?
在 C++ 中,我想让我的用户输入要在运行时创建的对象类型名称,并且根据我从他们那里得到的字符串,程序将实例化正确的对象(简而言之,我实现工厂方法模式)。但是,如果程序必须支持新的对象类型,则不允许修改现有代码。
那么是否有可能从方法中删除所有 if...else if...else if... 东西,并且仍然让我的程序实例化特定产品类型的正确对象(在众多对象中,只有在编译时才知道)?
我四处搜索找到了这个链接:Is there a way to instantiate objects from a string holding their class name? ,这似乎是我想要的,但我根本看不懂代码。
任何帮助将不胜感激。
【问题讨论】:
-
@CharlesB 你不需要反射,你可以使用工厂。
-
@LuchianGrigore:工厂是一种设计模式,反射是一种语言特性。如果您想要一个没有 if..else..else... 的工厂,您需要一种具有反射的语言或二进制插件架构,就像 Alessandro 的回答中一样
标签: c++ class reflection instantiation