【发布时间】:2011-11-16 21:18:12
【问题描述】:
我有一个类设计问题可以用这个例子来简化:
// 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 成员的每个调用之外,还有其他方法吗?
【问题讨论】:
-
我已经有一段时间没有做 C++ 了。但似乎你必须将父指针传递给你的类。您总是可以创建一个名为 parent 的属性并将其分配给父指针。
-
@Frank:问题在于编译器中的循环依赖。传递父指针并不是这里的棘手部分。