error: member access into incomplete type''; note: forward declaration of ''
error: member access into incomplete type''; note: forward declaration of ''
这里有一个结构体MAIN,有成员结构体A和结构体B,代码如下
// a.hpp
#ifndef _A_HPP_
#define _A_HPP_
struct A
{
int mem1;
};
#endif
// b.hpp
#ifndef _B_HPP_
#define _B_HPP_
#include "a.hpp"
#include "main.hpp"
struct MAIN;
struct A;
struct B{
int mem2;
MAIN* main;
A *aptr;
B(){
*aptr=this->main->a;
}
};
#endif
// main.hpp
#ifndef _MAIN_HPP_
#define _MAIN_HPP_
#include "a.hpp"
#include "b.hpp"
struct MAIN{
A a;
B b;
};
#endif
// main.cpp
#include "main.hpp"
int main(){
MAIN m;
return 0;
}
我想使用struct B中的aptr来访问同一个MAIN中的A,但是编译错误如
In file included from main.cpp:2:
In file included from ./main.hpp:6:
./b.hpp:15:25: error: member access into incomplete type 'MAIN'
*aptr=this->main->a;
^
./b.hpp:7:8: note: forward declaration of 'MAIN'
struct MAIN;
^
1 error generated.
错误是怎么产生的?我的代码应该使用 struct 而不是 class,hpp 而不是 h with cpp。无论如何要修复它?希望得到帮助
结构定义中的构造函数B::B
的定义引用了MAIN
的成员,但后者尚未完全定义。
您需要将构造函数 B::B
的主体移动到一个单独的文件中,即 b.cpp,并且在构建可执行文件时 link 和 main.cpp。
这里有一个结构体MAIN,有成员结构体A和结构体B,代码如下
// a.hpp
#ifndef _A_HPP_
#define _A_HPP_
struct A
{
int mem1;
};
#endif
// b.hpp
#ifndef _B_HPP_
#define _B_HPP_
#include "a.hpp"
#include "main.hpp"
struct MAIN;
struct A;
struct B{
int mem2;
MAIN* main;
A *aptr;
B(){
*aptr=this->main->a;
}
};
#endif
// main.hpp
#ifndef _MAIN_HPP_
#define _MAIN_HPP_
#include "a.hpp"
#include "b.hpp"
struct MAIN{
A a;
B b;
};
#endif
// main.cpp
#include "main.hpp"
int main(){
MAIN m;
return 0;
}
我想使用struct B中的aptr来访问同一个MAIN中的A,但是编译错误如
In file included from main.cpp:2:
In file included from ./main.hpp:6:
./b.hpp:15:25: error: member access into incomplete type 'MAIN'
*aptr=this->main->a;
^
./b.hpp:7:8: note: forward declaration of 'MAIN'
struct MAIN;
^
1 error generated.
错误是怎么产生的?我的代码应该使用 struct 而不是 class,hpp 而不是 h with cpp。无论如何要修复它?希望得到帮助
结构定义中的构造函数B::B
的定义引用了MAIN
的成员,但后者尚未完全定义。
您需要将构造函数 B::B
的主体移动到一个单独的文件中,即 b.cpp,并且在构建可执行文件时 link 和 main.cpp。