容器的元素如何访问其容器的 "owner"?

How can an element of a container access its container's "owner"?

我有这个架构:(简化)

class A {
    container<B*> c
}

class B {
    A* owner
}

这些 类 在不同的头文件中,对于这种架构,我必须包括:

啊啊啊我得到了循环依赖。我可以通过前向声明来解决这个问题,但我想解决设计问题。 (如果可能的话。)

A容器中的B如何在没有前向声明的情况下访问A?

或者前向声明是唯一的方法吗?

你说:

These classes are in different header files, and with this architecture I have to include:

  • B.h in A.h
  • A.h in B.h

不,你不知道。

前向声明就足够了,因为您在 A.h 中使用 B* 并在 B.h 中使用 A*

A.h

class B;
class A {
    container<B*> c
}

B.h

class A;
class B {
    A* owner
}
  1. 使用前向声明。这通过避免访问内联函数中的 class 成员(在 header 中)来限制你,但这对指针很有效。

  2. 使用模板设计

  3. 使用共享基础 class 获得您需要的所有接口。