C ++按字符串构造一个类

时间:2016-10-10 07:19:12

标签: c++ class abstract base derived

假设我有两个派生自同一基类的类。我想根据命令行输入实例化一个新的类对象。我能做到这一点:

#include <iostream>
#include "DerivedClass1.h"
#include "DerivedClass2.h"
using namespace std;

int main(int argc, char *argv[])
{
    if (argv[1] == "DERIVED CLASS 1") {
        DerivedClass1 *myClass = new DerivedClass1(argv[2]);
        myClass->doSomething();
    } else if (argv[1] == "DERIVED CLASS 2") {
        DerivedClass2 *myClass = new DerivedClass2(argv[2]);
        myClass->doSomething();
    }
}

但我想知道是否有更优雅的方式来做到这一点。我正在考虑创建一个抽象类工厂,或硬编码将字符串名称映射到类实例。 几个限制

1)我的基类是抽象的 - 它包含纯虚函数

2)我只能调用参数化构造函数

1 个答案:

答案 0 :(得分:8)

工厂功能应该可以正常工作:

BaseClass* create(std::string const& type, std::string const& arg)
{
    // Could use a map or something instead if there are many alternatives
    if (type == "DERIVED CLASS 1")
        return new DerivedClass1(arg);
    else if (type == "DERIVED CLASS 2")
        return new DerivedClass2(arg);
    else
        return nullptr;  // Or throw an exception or something else
}

用作

BaseClass* ptr = create(argv[1], argv[2]);