【问题标题】:Circular Dependency with forward declaration error带有前向声明错误的循环依赖
【发布时间】:2012-04-24 05:43:26
【问题描述】:

在 A.hpp 文件中我有一个结构,它有一个 B 类的指针

struct state
{
    B  *b;
};

在 A.hpp 文件中,我添加了前向声明,并将 B.hpp 文件包含在 A.cpp 文件中

//A.hpp
class B

在 B.hpp 文件中,函数使用在 A.hpp 中声明的状态作为函数的参数。

bool function_in_b(state *s)

我还在B.hpp文件中添加了A的前向声明,并在B.cpp文件中添加了A的头文件A.hpp。

//B.hpp
class A

所有头文件都有一个头保护。如果我尝试编译,它将找不到在 A.hpp 中声明的“状态”。因此,它不会找到匹配函数并抱怨候选人是

bool function_in_b(int *) 

我该如何解决这个问题?

【问题讨论】:

  • 遇到错误时您尝试编译哪个文件?

标签: c++


【解决方案1】:

在B.hpp 中,你说你前向声明了A,但不是state - 所以当它第一次看到function_in_b(state *s) 时,它不知道state 是什么。当您将A.hpp 包含在B.cpp 中时,为时已晚。您需要在B.hpp 中转发声明state,即

struct state;

bool function_in_b(state *s);

【讨论】:

    【解决方案2】:

    在B.hpp文件中,function_in_b(state *)的声明前,前向声明state类型:

    struct state;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-08
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-11
      • 1970-01-01
      相关资源
      最近更新 更多