假设我有两个派生自同一个基类的类。我想根据命令行输入实例化一个新的类对象。我可以这样做:
#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/