【发布时间】:2018-11-19 10:03:28
【问题描述】:
我有两个班,每个班都有几个孩子:
class ContainerGeneral {...};
class ContainerTypeA : ContainerGeneral {
public:
void doSomethingA();
};
class ContainerTypeB : ContainerGeneral {
void doSomethingB();
};
class InterpreterGeneral {
protected:
ContainerGeneral* container;
};
class InterpreterTypeA : InterpreterGeneral {
public:
void saveContainer(ContainerTypeA* cont) {
container = cont;
}
};
class InterpreterTypeB : InterpreterGeneral {
public:
void saveContainer(ContainerTypeB* cont) {
container = cont;
}
};
Interpreter 类用于对应类型的容器(A 到 A、B 到 B、General 到 General)。为此,我向InterpreterGeneral 添加了一个指向ContainerGeneral 对象的成员指针。我希望InterpreterGeneral 将此对象寻址为ContainerGeneral,但我希望继承的类能够将相同的容器寻址为适当类型的容器。我可以通过在寻址时将指针转换为继承的类来做到这一点(仅用于A 以节省空间的示例):
(ContainerTypeA*)container->doSomethingA();
或者通过添加一个继承类型的新成员指针,该指针将指向与容器相同的位置:
class InterpreterTypeA : InterpreterGeneral {
public:
void saveContainer(ContainerTypeA* cont) {
containerA = cont;
container = cont;
}
void doSomething() {
containerA->doSomethingA();
}
private:
ContainerTypeA* containerA;
};
在这种情况下,最佳做法是什么?有没有办法尽可能干净地做到这一点,无需每次都进行强制转换,也无需添加不包含任何“新”信息的新成员?
【问题讨论】:
-
是的,在
ContainerGeneral中创建一个虚拟的doSomething,不要费心从InterpreterGeneral继承。
标签: c++ inheritance