Fra*_*eri 1 c++ pointers class parent
我有一个类设计问题,可以通过这个例子简化:
// 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?
};
Run Code Online (Sandbox Code Playgroud)
除了使用通用指针或将父指针传递给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"
Run Code Online (Sandbox Code Playgroud)
虽然重新考虑你的设计可能会更好.