处理父/子类关系中的循环包含 [英] Dealing with circular inclusion in a parent/child class relationship
本文介绍了处理父/子类关系中的循环包含的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我创建了一个类,例如 Parent
,它与 Child
具有组合关系。父类保存了一个子类的列表。
Assume I've made a class, say Parent
, that has a composition relation with Child
. The parent class holds a list of children.
我想让所有的子类保存对父类的引用,所以每个子类都拥有一个 code>指针。
I want all children to hold a reference to the parent, so every child holds a Parent
pointer.
这将导致循环包含。我引用 parent.h 中的 Child
,我在中引用 Parent
child.h 。因此 Parent
需要包括 Child
,需要包括 Parent $ c $
This will cause circular inclusion. I refer to Child
in parent.h and I refer to Parent
in child.h. Therefore Parent
will need to include Child
, which needs to include Parent
.
推荐答案
p>您必须使用转发声明:
You'll have to use forward declaration:
//parent.h
class Child; //Forward declaration
class Parent
{
vector<Child*> m_children;
};
//child.h
class Parent; //Forward declaration
class Child
{
Parent* m_parent;
};
这篇关于处理父/子类关系中的循环包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文