假设我已经创建了一个类,比如说Parent,它与 具有组合关系Child。父类拥有一个子列表。
我希望所有孩子都持有对父母的引用,所以每个孩子都持有一个Parent指针。
这将导致循环包含。我指的Child是parent.h,我指的Parent是child.h。因此Parent将需要包含Child,哪些需要包含Parent。
解决此问题的最佳方法是什么?
假设我已经创建了一个类,比如说Parent,它与 具有组合关系Child。父类拥有一个子列表。
我希望所有孩子都持有对父母的引用,所以每个孩子都持有一个Parent指针。
这将导致循环包含。我指的Child是parent.h,我指的Parent是child.h。因此Parent将需要包含Child,哪些需要包含Parent。
解决此问题的最佳方法是什么?
您必须使用前向声明:
//parent.h
class Child; //Forward declaration
class Parent
{
vector<Child*> m_children;
};
//child.h
class Parent; //Forward declaration
class Child
{
Parent* m_parent;
};
Parent由于类中仅存储了一个指针,Child因此无需#include "parent.h"在child.h文件中执行 a 。class Parent;使用in的前向声明child.h而不是parent.h在其中包含。在 child ie 的源文件中,child.cpp您可以#include "parent.h"使用这些Parent方法。