gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:11:38 24 4
gpt4 key购买 nike

我有一个可以用这个例子简化的类设计问题:

// 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com