c++ 使用复杂的依赖项获取正确的转发声明



>问题

我收到以下编译错误:

错误:成员访问不完整的类型"IRB">

这发生在使用class IRB的第一行,在HG.h.

问题

  • 我在这里错过了什么?是类型定义导致了问题吗?

  • 在每个头文件上,正如你在下面看到的,我转发声明了我将要使用的类。

  • 更重要的是,我应该遵循什么过程才能正确处理?

头文件

typedef IRBBase__<true, true> IRB_BASE;  // typedef a template instantiation

IRB.h

#include "T.h"
#include "FH.h"
class FH; // FWD DCLR
class IRB : IRB_BASE {..};

FH.H

#include "T.h"
#include "IRB.h"
#include "HG.h"
class IRB;  // FWD DCLR
class HG;   // FWD DCLR
class FH {..};

HG.H

#include "T.h"
#include "FH.h"
#include "IRB.h"
#include "CU.h"
class FH;   // FWD DCLR
class IRB;  // FWD DCLR
class CU;   // FWD DCLR
class HG {..};

立方华

#include "T.h"
#include "IRB.h"
#include "FH.h"
class IRB;
class FH;
class CU {..};

编辑:让它工作

user0042建议之后,我通过将除HG.h以外的所有文件的标题移动到它们各自的.cc文件中来使其工作。HG.h我保留了前向声明和头文件。

这个答案是基于我收到的评论。

头文件中的函数声明可能正在使用我们不想包含的类,但这可能会导致循环依赖项。

所以解决方案是:

  • 将我们在头文件中提到的类的#include移动到源文件
  • 在头文件中对类进行forward declaration

这可以对标头中未使用的任何类执行此操作。如果我们使用标头,如以下示例HG.h,我们应该将#include保留在头文件中。

相关示例的解决方案

typedef IRBBase__<true, true> IRB_BASE;  // typedef a template instantiation

IRB.h

class FH; // FWD DCLR
class IRB : IRB_BASE {..};

FH.H

class IRB;  // FWD DCLR
class HG;   // FWD DCLR
class FH {..};

HG.H

#include "T.h"
#include "FH.h"
#include "IRB.h"
#include "CU.h"
class FH;   // FWD DCLR
class IRB;  // FWD DCLR
class CU;   // FWD DCLR
class HG {..
// some of the classes are used here, because some functions
// were too small and kept them in the header file (defined the function)
// if the same had happened with another of the headers, causing a
// cyclic include dependency, then I should have converted
// some of the function definitions into declarations, and move the
// implementation of the file in the source file (.cc)
};

立方华

class IRB;
class FH;
class CU {..};

最新更新