我有一个关于通告包含的问题,这让我发疯了:
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/