【问题标题】:create new object by string that repesent class name in c++ [duplicate]通过字符串创建代表c ++中类名的新对象[重复]
【发布时间】:2015-10-19 14:22:26
【问题描述】:

假设我有 3 个类,ClassA,ClassB,ClassC,它们都是从 classD 继承的,并且它们都具有仅获得一个 int 的构造函数,我想构建一个函数,在字符串中获取类名和一些 int ,并从类名返回新对象, 是否可以在 C++ 中不检查带有条件的类名?

我不想做这样的事情

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

【问题讨论】:

  • @cad: 不,走错路了……尽管可以说可以从中构建一个解决方案以及某种自动类型注册系统……如果您不介意@ 987654322@ 完全未指定。
  • 标准 C++ 没有为此提供任何工具。您必须使用平台相关库来搜索符号表并在其中解开名称。
  • 你需要使用工厂模式。

标签: c++


【解决方案1】:

一般来说,如果你想做类似的事情

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;
}

【讨论】:

    【解决方案2】:

    关注@SingerOfTheFall 所说的:

    您想要实现工厂设计模式。如果您进行谷歌搜索,则有很多选择:

    有些有一个 if 类型,正如你所拥有的那样,但有些则让你能够根据需要添加自己的工厂(上面列表中的最后 2 个)。

    对于实现 Factory 的 Qt 库,请查看 Qtilities 中的 Factories

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-02
      • 2014-12-23
      • 1970-01-01
      • 2012-12-20
      • 2011-02-26
      • 1970-01-01
      相关资源
      最近更新 更多