Dealing with circular inclusion in a parent/child class relationship

一曲冷凌霜 提交于 2020-01-03 15:12:32

问题


Assume I've made a class, say Parent, that has a composition relation with Child. The parent class holds a list of children.

I want all children to hold a reference to the parent, so every child holds a Parent pointer.

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.

What's the best way to work around this?


回答1:


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;
};



回答2:


Since only a pointer of Parent is stored inside the Child class there is no need to do a #include "parent.h" in the child.h file. Use the forward declaration of class Parent; in child.h instead of inclding parent.h in there. In the source file of child i.e. child.cpp you can do #include "parent.h" to use the Parent methods.



来源:https://stackoverflow.com/questions/4184351/dealing-with-circular-inclusion-in-a-parent-child-class-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!