转发声明 [英] forward declarations

查看:111
本文介绍了转发声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我已经包含相关的头文件时,为什么需要为类使用转发声明?它已经解决了我的问题,但困惑了我!

Why do I need to use forward declarations for a class when I am already including the relevant header file? It has fixed my problem but confused me!

本质上A类需要知道B类,反之亦然。我收到错误sytax错误 - 标识符之前,我包括前向声明。

essentially class A needs to know about class B and visa-versa. I was getting the error "sytax error - identifier" before I included the forward declarations. I was under the impression including a header file essentially meant you WERE declaring the other class where you put #include.

推荐答案

当你使用一个头文件时,有一个循环包含依赖,并且你正确地使用了包含守卫(因为你显然是),那么由于没有一个无限循环包含,编译器必须停止在某一点,它不知道内容的另一个头。

When you have a circular include dependency, and you're properly using include guards (as you clearly are), then since there isn't an infinite circular include, the compiler has to stop at some point, and it doesn't know about the contents of the other header. When you add the forward declaration it's able to compile your code.

例如, A 包括 B 。然后 B 包括 A ,但 A 并防止其第二次被评估。然后它回到 B ,它不知道从 Ah 的任何东西,因为包括guard,包容。然而,向前声明没有任何包含守卫,所以它正常进行。

For example, A includes B. Then B includes A, but A' include guard kicks in and prevents it from being evaluated a second time. Then it drops back into B which doesn't know about anything from A.h at that point because the include guard prevented its inclusion. The forward declaration however doesn't have any include guards around it so it proceeds as normal.

循环依赖没有什么内在错误,但我总是建议采取第二看看你的设计,看看是否可以把逻辑分解成第三类。转发声明是防止无限循环依赖的C ++机制。

There's nothing inherently wrong with circular dependencies, but I do always suggest taking a second look at your design to see if factoring out logic into a third class is possible. Forward declarations are the C++ mechanism to prevent infinitely circular dependencies.

这篇关于转发声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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