error: field 'b' has imcomplete type

在下面的程序中,在编译时会遇到下面的错误:

error: field 'b' has incomplete type

域b是一个不完备的类型,即class B的声明不完备

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class A
 5 {
 6     private:
 7        class B b;
 8     public:
 9         A(){cout<<"this is A constructor!"<<endl;}
10 };
11 
12 class B
13 {
14     public:
15       B(){cout<<"this is B constructor!"<<endl;}
16 };
17 
18 int main()
19 {
20     A a;
21     return 0;
22 }

分析:

出现该错误的原因是在声明class A的成员变量b时, b的类型 class B 还没有定义。

类或结构体的前向声明只能用来定义指针对象,当编译到7 class B b; 时还没有发现定义,

不知道该类或者结构的内部成员,没有办法具体的构造一个对象。

Debug:

将class B的定义放到class A之前即可编译通过

那么还有哪些情况下会出现这样的情况呢?

1. 在使用设计模式时,我们时常会用到工厂模式,当我们需要添加工序类的时候,往往习惯现在工厂类中定义工序的对象,然后在工厂类之后定义工序类,从而出现本文中的错误。

    比较好的解决方法是,将工序类单独存放到一个头文件中,然后在工厂类所在文件中引用该头文件。

2. 在使用STL容器的时候,往往忘记添加相应的头文件。如#include <vector>; #include <list>; #include <deque>等

原文地址:https://www.cnblogs.com/double-win/p/3683550.html