用表示c++中类名的字符串创建新对象

create new object by string that repesent class name in c++

本文关键字:新对象 创建 对象 字符串 c++ 表示      更新时间:2023-10-16

假设我有3个类,ClassA,ClassB,ClassC,所有它们都继承自classD,并且它们都有构造函数,只获得一个int,我想建立一个函数,以字符串形式获取类名和一些int,并从类名返回新对象,在c++中可以不检查类名和条件吗?

我不想那样做

if(className == "classA")
 return new ClassA(Num)
else if(className == "classB")
 return new Classb(Num) ....

一般来说,如果你想做一些像

Base * createObject(string name)
{
    return new <name_as_a_type>();
}

你需要一种带有反射的语言,所以在c++中是不可能的,但在ruby中是可能的。如果你特别讨厌if条件,你可以在c++中做一些奇怪的事情,尽管我不知道你为什么要这样做:

class Base
{
public:
    Base(int v)
    {
        std::cout << "base" << v << std::endl;
    }
};
class Derived : public Base
{
public:
    Derived(int v)
        : Base(v)
    {
        std::cout << "derived" << v << std::endl;
    }
};
class BaseFactory
{
public:
    virtual Base * create(int value)
    {
        return new Base(value);
    }
};
class DerivedFactory : public BaseFactory
{
    Base * create(int value) override
    {
        return new Derived(value);
    }
};
Base * createAwesomeness(string className, int parameter)
{
    static std::map<string, BaseFactory *> _map = {
        {"Base", new BaseFactory()},
        {"Derived", new DerivedFactory()}
    };
    auto it = _map.find(className);
    if(it != _map.end())
        return it->second->create(parameter);
    return nullptr;
}
int main()
{
    auto b = createAwesomeness("Base", 0); //will construct a Base object
    auto d = createAwesomeness("Derived", 1); //will construct a Derived object
    return 0;
}

跟进@SingerOfTheFall说的话:

你想要实现工厂设计模式。如果你在谷歌上搜索,有很多选项:

  • http://www.sourcetricks.com/2008/05/c-factory-pattern.html .ViUFK2xStBd
  • https://sourcemaking.com/design_patterns/factory_method
  • http://www.codeproject.com/Articles/363338/Factory-Pattern-in-Cplusplus
  • http://blog.fourthwoods.com/2011/06/04/factory-design-pattern-in-c/

一些有一个类型化的if,就像你所拥有的那样,但其他的则提供了根据需要添加自己的工厂的能力(上面列表中的最后两个)。

对于实现工厂的Qt库,请查看qutilities

中的工厂