包含头文件时出错

时间:2012-04-15 04:14:27

标签: c++ c++11

您好我有两个A和B班。 在A我正在使用B的头文件,以便我可以为B创建一个实例(例如B * b)和我在B类中做的事情,即包括A的头文件并为A创建实例(例如B中的A * a)。

当我在A中包含A的头文件时,它在A.h

中给出了以下错误
1>c:\Bibek\A.h(150) : error C2143: syntax error : missing ';' before '*'
1>c:\Bibek\A.h(150)(150) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\Bibek\A.h(150)(150) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

1 个答案:

答案 0 :(得分:4)

听起来你是以循环方式包含头文件(A.h包括B.h,其中包括A.h)。使用标题保护意味着当B.h在上面的场景中包含A.h时,它会跳过它(由于现在活动包括A.h的保护),因此在解析B.h时,尚未定义A.h中的类型。

要修复,您可以使用前向声明:

// A.h
#ifndef A_H
#define A_H

// no #include "B.h"

class B; // forward declaration of B
class A {
  B* b;
};

#endif
同样适用于B.h

这允许您使用前向声明的类的指针(例如,在成员变量的声明,成员函数声明中),但不能在标题中以任何其他方式使用它。

然后在A.cpp中你需要有B.h的正确定义,所以你要包含它:

// A.cpp

#include "A.h"
#include "B.h" // get the proper definition of B

// external definitions of A's member functions

这种结构避免了循环包含头文件,同时允许完全使用类型(在.cpp文件中)。

注意:关于不支持default int的错误发生在编译器在包含Bh时没有A的正确定义时(C语言允许对未知类型的默认int定义,但这在C ++中是不允许的)