5

假设我已经创建了一个类,比如说Parent,它与 具有组合关系Child。父类拥有一个子列表。

我希望所有孩子都持有对父母的引用,所以每个孩子都持有一个Parent指针。

这将导致循环包含。我指的Childparent.h,我指的Parentchild.h。因此Parent将需要包含Child,哪些需要包含Parent

解决此问题的最佳方法是什么?

4

2 回答 2

8

您必须使用前向声明:

//parent.h
class Child; //Forward declaration
class Parent
{
    vector<Child*> m_children;
};

//child.h
class Parent; //Forward declaration
class Child
{
    Parent* m_parent;
};
于 2010-11-15T12:37:28.590 回答
3

Parent由于类中仅存储了一个指针,Child因此无需#include "parent.h"child.h文件中执行 a 。class Parent;使用in的前向声明child.h而不是parent.h在其中包含。在 child ie 的源文件中,child.cpp您可以#include "parent.h"使用这些Parent方法。

于 2010-11-15T12:36:26.223 回答