C++循环包括内部结构

C++ circular includes with internal structs

本文关键字:结构 包括内 循环 C++      更新时间:2023-10-16

我有一个关于循环包含的问题,这让我很疯狂:

主.cpp

#include "A.hpp"
#include "B.hpp"
int main()
{
    A a();
    B b();
    return 0;
}

A.hpp

#ifndef _CLASS_A
#define _CLASS_A
#include "B.hpp"
class A
{
    public: 
        B* b;
        struct A_t
        {
            int id;
        };
};
#endif

B.马力

#ifndef _CLASS_B
#define _CLASS_B
#include "A.hpp"
class B
{
    class A;  //Ok, with that I can use the class A
    public: 
        int a;
        A* b;  // That work!
        A::A_t *aStruct; // Opss! that throw a compilation error.
};
#endif

问题是:¿如何在 B 类中使用 A_t 结构?

我试图添加一个转发声明,例如:

struct  A::A_t;

但这显然确实有效。

A.h中的包含替换为前向声明。

#ifndef _CLASS_A
#define _CLASS_A
class B;
class A
{
    public: 
        B* b;
        struct A_t
        {
            int id;
        };
};
#endif

另外,请注意

A a();
B b();

不会创建类的两个实例,但它们是函数声明。你想要

A a;
B b;