C++ 两个类相互包含,什么';下一个代码怎么了?

C++ 两个类相互包含,什么';下一个代码怎么了?,c++,class,C++,Class,我有两个班,“A”和“B” A.h B.h 但是,这并不能带来成功。谁能告诉我A::Test*如何成为B中的成员,你有一个循环依赖,头文件A.h需要B.h,它需要A.h等等 打破循环的唯一方法是不将一个头文件包含在另一个头文件中 在您的例子中,头文件B.h确实需要A.h头文件,因为类B使用类A的成员,所以您需要更改头文件A.h不包括B.h。这很简单,因为classA实际上不使用或不需要知道classB的任何内容,只有classB存在,所以更改A.h如下: #ifndef _A_H__ #defi

我有两个班,“A”和“B”

A.h B.h
但是,这并不能带来成功。谁能告诉我
A::Test*
如何成为
B
中的成员,你有一个循环依赖,头文件
A.h
需要
B.h
,它需要
A.h
等等

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

在您的例子中,头文件
B.h
确实需要
A.h
头文件,因为类
B
使用类
A
的成员,所以您需要更改头文件
A.h
不包括
B.h
。这很简单,因为class
A
实际上不使用或不需要知道class
B
的任何内容,只有class
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

写B.h如下:

#ifndef _B_H__
#define _B_H__

class A;
class B
{
public:
    A *a;
    A::Test* qq;
};
#endif

编译错误是什么?当它是
c++
概念时,为什么要标记
c
?[删除]在此处“A::Test*qq;”上使用未定义的“A”,这将无法编译。您需要定义
A
来使用嵌套名称,如
A::Test
#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
#ifndef _B_H__
#define _B_H__

class A;
class B
{
public:
    A *a;
    A::Test* qq;
};
#endif