【问题标题】:C++ Construct a class by stringC++通过字符串构造一个类
【发布时间】:2017-02-18 13:36:59
【问题描述】:

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

#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) 我只能调用参数化构造函数

【问题讨论】:

  • argv[1] == "DERIVED CLASS 1" 是个错误
  • 您必须创建一个工厂设计模式。此链接可能会有所帮助sourcemaking.com/design_patterns/factory_method/cpp/1
  • @M.M 有什么问题?
  • 它比较argv[1]是否指向存储"DERIVED CLASS 1"的内存位置(它永远不会)

标签: c++ class abstract base derived


【解决方案1】:

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

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

【讨论】:

  • 为什么类型必须是字符串 const &?
  • @ahhhhhjulie 您不必将其作为对常量字符串对象的引用,只需简单的std::string 就可以在您的情况下使用。但是,如果你想用其他字符串调用它,传递引用意味着更少的复制。传递对常量的引用意味着您可以传递字符串文字或临时对象,并且还告诉编译器该函数不会修改可能启用某些优化的函数(虽然在这种情况下不太可能)并简化其语义检查。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-03
  • 2022-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多