我有两个类
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。
如果Derived
和Base
实际上完全不相关,那么答案是否定的。
如果您有私有继承权,则必须滚动自己的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());
}