gpt4 book ai didi

c++ - 两个类相互包含,下一段代码有什么问题?

转载 作者:行者123 更新时间:2023-11-28 02:38:04 24 4
gpt4 key购买 nike

我有 2 个类,“A”和“B”

啊.h

#ifndef _A_H__
#define _A_H__
#include "B.h"

class A
{
public:
struct Test
{
int qq;
};
B *b;
};
#endif

B.h

#ifndef _B_H__
#define _B_H__
#include "A.h"
class A;
class B
{
public:
A *a;
A::Test* qq;
};
#endif

但是,这不能编译成功。谁能告诉我 A::Test* 如何作为 B

中的成员

最佳答案

你有一个循环依赖,头文件 A.h 需要 B.h 而它需要 A.h 等等。

打破循环的唯一方法是不在另一个头文件中包含一个头文件。

在你的例子中,头文件 B.h 确实需要 A.h 头文件,因为类 B 使用类 的成员A,因此您需要更改头文件 A.h 不包含 B.h。这很简单,因为类 A 并不真正使用或需要了解类 B 的内容,只有类 B 存在, 所以像这样改变 A.h:

#ifndef _A_H__
#define _A_H__

// Declare that class B exists
class B;

class A
{
public:
struct Test
{
int qq;
};

// The compiler knows that a class B exists, so we can have a pointer
// to that class here. To declare a pointer to some type, the compiler
// doesn't need the actual definition of the type, just know that the
// type exists.
B *b;
};
#endif

关于c++ - 两个类相互包含,下一段代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26861112/

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