C++ 中基本和派生 class 对象的树结构
A Tree structure of base and derived class objects in C++
我有两个classes
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();
}
我可以从两个指向 Base class 对象的指针创建派生对象。但我也想从两个指向 Derived class 对象的指针创建一个 Derived 对象。有什么好的方法吗?
假设你打算Derived
成为一个class公开派生自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());
}
我有两个classes
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();
}
我可以从两个指向 Base class 对象的指针创建派生对象。但我也想从两个指向 Derived class 对象的指针创建一个 Derived 对象。有什么好的方法吗?
假设你打算Derived
成为一个class公开派生自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());
}