我对C++相对陌生,现在在我的设计中面临一个问题:不可避免地需要进行向下转换。我知道这通常是糟糕设计的标志,所以我想知道有什么更好的方法来解决这个问题。
我有一个代表几何帧树并允许它们之间进行几何变换的类 Frame
:
class Frame
{
private:
Frame *_parent;
std::vector<Frame*> _children;
public:
Frame* getParent() const;
std::vector<Frame*> getChildren() const;
... (extra methods for geometrical transformations)
}
我现在想创建一个新的Frame
子类,MechanicalFrame
,以添加一些处理动态属性的功能。
class MechanicalFrame
{
private:
double mass;
...
public:
void compute();
}
我的问题是,“compute”方法需要实现一些递归的逻辑,因此它可能包含以下内容:
MechanicalFrame::compute()
{
for element in getChildren():
element.compute();
}
然而,由于
getChildren
返回一个Frame*
的vector
而不是MechanicalFrame*
,因此我需要在这一点上进行static_cast
。我已经认真思考了这个问题,但我找到的解决方案都不能完全令我满意:解决方案1)静态转换:某种程度上表明设计不良。
解决方案2)将计算方法添加到基类(
Frame
)中,并使用虚拟实现,即抛出异常:强制基于派生类的父类实现似乎很不自然。解决方案3)完全分离
MechanicalFrame
和Frame
:这意味着需要重新实现Frame
中已有的许多功能。非常感谢您的帮助。提前致以万分感谢 :)
Frame::compute()
并将其设为virtual
。问题是 - 你打算实例化基类吗?也许将Frame
定义为抽象类会是个好主意。 - pSoLTMechanicalFrame::getChildren()
中的所有Frame*
指针都指向MechanicalFrame
实例,那么使用static_cast
应该没有问题。请确保在调试版本中使用dynamic_cast
+assert
来捕获错误。 - Vittorio RomeoaddChild
/getChildren
方法。 - alexeykuzmin0