C++ 循环包含内部结构

标签 c++ struct circular-dependency

我有一个关于通告包含的问题,这让我发疯了:

main.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.hpp

#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;

关于C++ 循环包含内部结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13376843/

相关文章:

java - OpenCV JNI : Java/native handling of Mat - possibility for delete getting called twice?

c - c中的bsearch函数和结构

由于枚举类嵌套,C++ 循环依赖

excel - 如何同步多个Excel输入单元格

c++ - 这是循环依赖吗

c++ - 如何追踪 LLVM verifyFunction 错误 "Expected no forward declarations!"?

c++ - 可变参数模板的声明点

c++ - 尝试分配函数指针时获取 "Void value not ignored as it ought to be"

c++ - 库达和库布拉斯 :call a global function after using cublas

c++ - 什么时候会出现结构包装问题?