问题描述
每当类声明使用另一个类作为指针时,使用类转发声明而不是包括头文件以便预先避免循环依赖的问题是有意义的吗?所以,而不是:
//文件Ch
#includeAh
#include Bh
class C {
A * a;
B b;
...
};
请执行以下操作:
// file Ch
#includeBh
class A;
class C {
A * a;
B b;
...
};
//文件C.cpp
#includeCh
#includeAh
...
有什么原因为什么不在可能的地方这样做?
解决方案前向声明方法总是更好。 (我不能想到一个情况,包括一个文件,你可以使用一个向前的声明是更好,但我不会说它总是更好只是为了情况下)。
没有前进声明类的缺点,但我可以想到一些不必要的包含头的缺点:
-
更长的编译时间,因为包括
Ch
的所有翻译单元也将包括Ah
,尽管他们可能不需要它。 -
可能包含不需要间接的其他标题
您不需要 -
您可能需要重新编译包含该标题的源文件(@PeterWood)
Whenever a class declaration uses another class only as pointers, does it make sense to use a class forward declaration instead of including the headerfile in order to pre-emptively avoid problems with circular dependencies? so, instead of having:
//file C.h
#include "A.h"
#include "B.h"
class C{
A* a;
B b;
...
};
do this instead:
//file C.h
#include "B.h"
class A;
class C{
A* a;
B b;
...
};
//file C.cpp
#include "C.h"
#include "A.h"
...
Is there any reason why not to do this wherever possible?
The forward-declaration method is almost always better. (I can't think of a situation where including a file where you can use a forward declaration is better, but I'm not gonna say it's always better just in case).
There are no downsides to forward-declaring classes, but I can think of some downsides for including headers unnecessarily:
longer compilation time, since all translation units including
C.h
will also includeA.h
, although they might not need it.possibly including other headers you don't need indirectly
polluting the translation unit with symbols you don't need
you might need to recompile source files that include that header if it changes (@PeterWood)
这篇关于应该使用转发声明,而不是包括在任何可能的地方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!