在我的设计中,我有1个基类和N个子类:
class BaseClass {
public:
BaseClass() {}
virtual void execute(int16_t* l_image);
}
class ChildClass1: public BaseClass {
public:
ChildClass1() {}
void execute(int16_t* l_image);
}
class ChildClass2: public BaseClass {
public:
ChildClass2() {}
void execute(int16_t* l_image);
}
int main {
std::vector<std::string> class_names;
// read list of string from file using get_names(), omitted for brevity of the example
class_names = get_names();
std::vector<BaseClass> all_layers;
for (size_t name_idx = 0; name_idx < class_names.size(); name_idx++) {
BaseClass new_layer;
if (class_names[name_idx] == "ChildClass1")
new_layer = ChildClass1();
if (class_names[name_idx] == "ChildClass2")
new_layer = ChildClass2();
all_layers.push_back(new_layer);
}
for (size_t layer_idx = 0; layer_idx < all_layers.size(); layer_idx++) {
all_layers[layer_idx].execute();
}
}
我有一个BaseClass的std:vector,实际上包含了differend ChildClassN的实例。现在,如果我遍历在每个对象上调用“ execute”方法的数组,则将调用BaseClass而不是子级。在不知道自己有哪个孩子的情况下,如何调用子方法?
我在网上发现的唯一一件事就是我在做的是某种不好的设计,但是我不确定我会选择什么替代品...
谢谢