如何实例化一个只知道其名称的对象?
可能的重复:
有办法吗从保存类名的字符串实例化对象?
在 C++ 中,我想让用户输入要在运行时创建的对象类型名称,并且根据我从他们那里获得的字符串,程序将实例化正确的对象(简而言之,我' m 实现工厂方法模式)。但是,如果程序必须支持新的对象类型,则不允许修改现有代码。
那么是否有可能从方法中删除所有 if...else if...else if... 的内容,并且仍然让我的程序实例化特定产品类型的正确对象(在许多中,仅已知在编译时)?
我的搜索找到了这个链接: 有没有办法从保存类名的字符串中实例化对象? 看来这就是我想要的,但我根本无法理解代码。
任何帮助将不胜感激。
Possible Duplicate:
Is there a way to instantiate objects from a string holding their class name?
In C++, I want to have my user enter the object type name to be created at run-time, and, depending on the string I get from them, the program will instantiate the correct object (in short, I'm implementing factory method pattern). However, if the program has to support a new object type, then modifying existing code is not allowed.
So is it possible to remove all the if...else if...else if... stuff from the method, and still have my program instantiate a correct object of a specific product type (out of many, which are known only at compile time)?
My searching around got me this link: Is there a way to instantiate objects from a string holding their class name? and it seems it's what I want but I can't understand the code at all.
Any help would be really appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅当所有必需的类都派生自某个公共基类时,这才有效,并且您通常仅限于使用基接口(尽管您可以通过一些额外的努力来解决这个问题)。这是一种方法:
现在您可以从新代码添加新的派生类:
要创建一个类,您只需调用
Base * p = Base::create_from_string("Foo");
。This will only work if all the required classes are derived from some common base class, and you will generally be limited to using the base interface (though you can work around that with some additional effort). Here's one approach:
Now you can add new derived classes from your new code:
To create a class, you simply call
Base * p = Base::create_from_string("Foo");
.你可以通过实现类似插件系统的东西来做到这一点。我已经在 Linux 中使用 dlopen 实现了这一点。程序不需要修改,但您只需要添加新的类作为将在运行时加载的动态库。
您可以从这里开始了解更多信息:C++ dlopen mini HOWTO
You can do that implementing something like a plugin system. I've implemented this in Linux with dlopen. The program doesn't need to be modified, but you need only add new classes as dynamic libraries that will be loaded at runtime.
You can start here for more info: C++ dlopen mini HOWTO