转发声明/何时最好包括标题? [英] Forward declaration / when best to include headers?

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

问题描述

我很清楚什么时候可以/不能使用转发声明,但我仍然不能确定一件事。

I'm pretty clear on when I can/can't use forward declaration but I'm still not sure about one thing.

我知道我不得不迟早包括一个标题来解引用类A的对象。
我不清楚是否更有效的做一些事情。

Let's say I know that I have to include a header sooner or later to de-reference an object of class A. I'm not clear on whether it's more efficient to do something like..

class A;
class B
{
   A* a;
   void DoSomethingWithA();
};

然后在cpp中有类似...

and then in the cpp have something like..

#include "A.hpp"
void B::DoSomethingWithA()
{
   a->FunctionOfA();
}

或者我也可以在A的头文件地点?
如果前者更有效,那么我会感激的,如果有人清楚地解释为什么我怀疑它与编译过程有关,我可以随时了解更多。

Or might I as well just include A's header in B's header file in the first place? If the former is more efficient then I'd appreciate it if someone clearly explained why as I suspect it has something to do with the compilation process which I could always do with learning more about.

推荐答案

尽可能使用前向声明(如您的示例中所示)。这减少了编译时间,但更重要的是最小化头和库依赖关系的代码,不需要知道和不关心实现细节。

Use forward declarations (as in your example) whenever possible. This reduces compile times, but more importantly minimizes header and library dependencies for code that doesn't need to know and doesn't care for implementation details. In general, no code other than the actual implementation should care about implementation details.

以下是Google对此的理由:标题文件依赖关系

Here is Google's rationale on this: Header File Dependencies

这篇关于转发声明/何时最好包括标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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