C++ 中基类和派生类对象的树结构



我有两个类

class Base {
explicit Base();
virtual void update();
}
class Derived : Base {
std::shared_ptr<Base> left, right;

explicit Derived(std::shared_ptr<Base> left, std::shared_ptr<Base>);
virtual void update() override;
void special_update();
}

我可以从两个指向基类对象的指针创建一个派生对象。但我也想从两个指向派生类对象的指针创建一个派生对象。有什么好方法可以做到这一点吗?

假设你打算Derived是一个从Base公开派生的类,你正在寻找std::static_pointer_cast可以将一种类型的std::shared_ptr转换为另一种类型的std::shared_ptr

Derived(std::shared_ptr<Derived> left, std::shared_ptr<Derived> right)
: Derived(
std::static_pointer_cast<Base>(left),
std::static_pointer_cast<Base>(right)) {
}

如果您不知道由于继承关系,该类型始终可转换为Base,您也可以使用std::dynamic_pointer_cast(例如,从Base转换为Derived时)。

另请注意,如果您打算在std::shared_ptr<Base>物体中拖曳Derived物体,则很可能需要有一个virtual ~Base() {}。否则,您很可能会产生 UB。


如果DerivedBase实际上完全不相关,那么答案是否定的


如果您有私有继承权,则必须滚动自己的static_pointer_cast版本:

// in Derived:
static std::shared_ptr<Base> static_pointer_cast(std::shared_ptr<Derived> const& r) noexcept {
return std::shared_ptr<Base>(r, r.get());
}

最新更新