是否可以在像 C++ 中的体系结构这样的接口中使用动态转换

is it possible to use dynamic cast in an interface like architecture in c++

我对 C++ 有点陌生,我遇到了这个问题:

是否可以通过以下方式访问 class Object 中的 *parent 指针:

class Object      (*parent ptr here pointing to the parent or nullPtr if it is  root)
class IStorage   <- which contains the ability of an object to nest children
class ISearch    <- which contains the ability to search in a given container
class Container : public virtual Object,public virtual IStorage,public virtual Isearch   <-  resulting class

现在在 Istorage 中我有一个方法 virtual void addChild(T* obj) 添加 child 应该更新 child 的 *parent 但我不知道我是否可以访问它。

是否可以从 IStorage 获取指向 Object 的指针 这种架构不好吗?我应该只选择像架构这样的通用树吗?

提前致谢

恐怕没有破解的方法,你可以做的是向 IStorage 添加一个 virtual Object* getObject() = 0; 并在 Container 中这样定义它:Object* getObject() override { return this; }.

另一种方法(在我看来对 OOP 更友好)是向 IStorage 添加一个虚拟方法,例如:virtual void updateAfterAddChild() = 0; 并在 Container 中实现它,这将调用 Object 上的适当方法 class.

如果 IStorage 知道其内容的结构,父指针应该位于那里,这样就可以访问它。

否则,也许您应该从 IStorage 派生 Object 并在那里覆盖 addChild。