我有一个可以通过以下示例简化的类设计问题:
// foo.h
#include "foo2.h"
class foo
{
public:
foo2 *child;
// foo2 needs to be able to access the instance
// of foo it belongs to from anywhere inside the class
// possibly through a pointer
};
// foo2.h
// cannot include foo.h, that would cause an include loop
class foo2
{
public:
foo *parent;
// How can I have a foo pointer if foo hasn't been pre-processed yet?
// I know I could use a generic LPVOID pointer and typecast later
// but isn't there a better way?
};
除了使用通用指针或将父指针传递给foo2成员的每次调用之外,还有其他方法吗?
最佳答案
如果仅使用指针,则不需要包含文件;如果将它们包含在.cpp文件中,则不会造成循环麻烦:
// foo.h
class foo2; // forward declaration
class foo
{
public:
foo2 *child;
};
// foo2.h
class foo;
class foo2
{
public:
foo *parent;
};
//foo.cpp
#include "foo.h"
#include "foo2.h"
//foo2.cpp
#include "foo2.h"
#include "foo.h"
尽管重新考虑设计可能会更好。
关于c++ - C++:指向包含子级的类的父级指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8158851/