C++:指向包含子级的类的父级指针
我有一个可以用这个例子简化的类设计问题:
// 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 成员的每次调用之外,还有其他方法吗?
I have a class design problem that could simplified with this example:
// 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?
};
Is there any other way other than using a generic pointer or passing the parent pointer to every call of foo2 members?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您只使用指针,则不需要包含该文件,并且如果将它们包含在 .cpp 文件中,则不会遇到循环问题:
尽管重新考虑设计可能会更好。
You don't need to include the file if you're only using a pointer, and you won't have looping trouble if you include them in .cpp files:
Although you may be better off by rethinking your design.
前向声明是一个朋友:
不过,正如 Pubby 所说,需要相互了解的类可能应该只是一个类,或者可能是一个具有两个成员的类,这两个成员都知道父类,但不能作为两个成员方式关系。
就为人父母和通用而言:
Forward declaration is a friend:
As Pubby says, though, classes that need to know about each other should probably just be one class, or maybe a class, with two members, both of which know about the parent class, but not as a two-way relationship.
As far as parenthood and being generic goes:
您应该使用前向声明并将头文件包含在您的 cpp 中
You should use forward declarations and include the header files in your cpp
使用 前向声明 告诉编译器
foo2
是一个随后定义的类。Use a forward declaration to tell the compiler that
foo2
is a class that will be defined subsequently.