用表示c++中类名的字符串创建新对象
create new object by string that repesent class name in c++
假设我有3个类,ClassA,ClassB,ClassC,所有它们都继承自classD,并且它们都有构造函数,只获得一个int,我想建立一个函数,以字符串形式获取类名和一些int,并从类名返回新对象,在c++中可以不检查类名和条件吗?
我不想那样做
if(className == "classA")
return new ClassA(Num)
else if(className == "classB")
return new Classb(Num) ....
一般来说,如果你想做一些像
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;
}
跟进@SingerOfTheFall说的话:
你想要实现工厂设计模式。如果你在谷歌上搜索,有很多选项:
- http://www.sourcetricks.com/2008/05/c-factory-pattern.html .ViUFK2xStBd
- https://sourcemaking.com/design_patterns/factory_method
- http://www.codeproject.com/Articles/363338/Factory-Pattern-in-Cplusplus
- http://blog.fourthwoods.com/2011/06/04/factory-design-pattern-in-c/
一些有一个类型化的if,就像你所拥有的那样,但其他的则提供了根据需要添加自己的工厂的能力(上面列表中的最后两个)。
对于实现工厂的Qt库,请查看qutilities
相关文章:
- C++ 如何在将新对象分配给另一个对象时创建新对象
- 重用对象与创建新对象
- C++,创建新对象时类的对象更改
- 创建新对象并立即为其设置属性时出现编译器错误
- 我应该如何在这个房间中创建一个新对象 - opengl
- 如何创建一个C ++函数,该函数在每次用户输入新数据时创建新对象
- 在 JNI 中创建新对象
- C++如何为向量中的每个元素创建一个新对象?
- 如何使用安置新操作员创建对象数组
- 从指针参考C 创建一个新对象
- 我如何在参考上使用数据成员而不使用新关键字创建对象
- 为对象指针数组的每个空索引创建新对象
- 在创建新对象时,尝试将参数提供给JNI对象的构造函数时会出现错误
- 我的代码有效,但 setter 不会创建新对象,所以我得到错误的结果
- 如何使用动态内存分配在现有数组中创建和添加新对象
- 我如何从数组中创建一个新对象,该数组在C 中保存不同的对象
- 在C++语言中,如何创建一个指向数组的指针的新对象?
- 使用另一个(现有)对象创建新对象时会发生什么情况?
- 动态创建新对象的最佳方法
- 通过使用新操作员创建对象会导致未解决的外部符号错误C FTGL