循环依赖与前向声明错误 [英] Circular Dependency with forward declaration error

查看:216
本文介绍了循环依赖与前向声明错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  struct state 
{
B * b;
};

在A.hpp文件中,我添加了一个forward声明, cpp文件

  // A.hpp 
类B
pre>

在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 b $ b  

如何解决这个问题?



提前感谢

解决方案

B.hpp -declared A ,但不是 state - 所以当它第一次看到 function_in_b )它不知道状态是什么。当您在 B.cpp 中包含 A.hpp 时,已经太晚了。您需要在 B.hpp 中转发声明 state ,即

  struct state; 

bool function_in_b(state * s)


In A.hpp file I have a structure, which has a pointer of B class

struct state
{
    B  *b;
};

In A.hpp file, I added a forward declaration and I included B.hpp file in A.cpp file

//A.hpp
class B

In B.hpp file, a function uses the state, which declared in A.hpp as an argument on the function.

bool function_in_b(state *s)

I also added a forward declaration of A in B.hpp file and I added the header file of A, A.hpp in B.cpp file.

//B.hpp
class A

All header files have a header guard. If I try to compile, it won't find 'state' declared in A.hpp. Thus, it won't find the matching function and complains the candidates are

bool function_in_b(int *) 

How do I fix this problem?

Thanks in advance

解决方案

In B.hpp, you say you forward-declared A, but not state - so when it first sees function_in_b(state *s) it doesn't know what state is. By the time you include A.hpp in B.cpp it's too late. You need to forward declare state in B.hpp, i.e.

struct state;

bool function_in_b(state *s);

这篇关于循环依赖与前向声明错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆