C++:指向包含子类的类的父指针

标签 c++ class pointers 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?
};

除了使用通用指针或将父指针传递给 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++:指向包含子类的类的父指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8158851/

相关文章:

python - 使用多处理时无法 pickle 静态方法

java - 我如何在方法中使用 (WebElement webdriverWait Until element is clickable) 并调用该方法以供重新使用

c - 指针中的指针指针中的指针

C++ 字符串操作,字符串下标超出范围

c++ - 将文本文件读入二维数组 C++

javascript - 使用 javascript 将类添加到 div 元素

c - 以结构体数组指针作为参数的函数,C 语言

c - 确定分配给指针的地址的大小

c++ - 在大型 C/C++ 项目的编译时使用 GNU m4

c++ - 如何编写适用于 vector 或 map 迭代器的自定义算法