具有前向声明错误的循环依赖

时间:2012-04-11 21:12:46

标签: c++

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

struct state
{
    B  *b;
};

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

//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中声明的'state'。因此,它不会找到匹配函数并抱怨候选人

bool function_in_b(int *) 

如何解决此问题?

2 个答案:

答案 0 :(得分:2)

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

struct state;

bool function_in_b(state *s);

答案 1 :(得分:1)

在B.hpp文件中,在声明function_in_b(state *)之前,转发声明state类型:

struct state;