C++通过字符串构造类

标签 c++ class abstract radix 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) 我只能调用参数化构造函数

最佳答案

工厂函数应该可以正常工作:

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]);

关于C++通过字符串构造类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39953061/

相关文章:

css - 在 CSS 中将一个类导入另一个类

java - 使用来自不同类的 Java 枚举?

c++ - 无法将 initializer_list 转换为类 <int>

c++ - 在 C++ 中使用 continue 语句打印字符

javascript - 在React JavaScript中,如何在另一个类中调用一个类?

c++ - 抽象类继承另一个具有相同函数名的抽象类

java - 为什么 Java 不允许多重继承,但允许遵循具有默认实现的多个接口(interface)

inheritance - TablePerHierarchy 对于抽象类总是 false?

c++ - 当 Qt Slot 位于通过 std::async 创建的线程上时,它不会被调用

c++ - 明确默认的构造函数和成员变量的初始化