#include 如何在 C++ 中工作?
如果一个库包含在一个类头中,然后这个头包含在另一个类中,我是否必须再次包含该库?
If a library is included in a class header and then this header is included in another class do I have to include the library again?
例如:
#ifndef A_H
#define A_H
#include<someLibrary.h>
class A{
...
}
#endif
然后另一个类包含 A.h 标头
Then another class includes the A.h header
#include<A.h> //include class A
class B{
...
}
我必须在 B 类中包含someLibrary.h"吗?
Do I have to include the "someLibrary.h" in class B?
推荐答案
不,#include
s 是可传递的.
但是,如果您的第二个文件本身使用 someLibrary 中的符号,则重新包含标题是一种不错的方式.这样你就不会希望和祈祷"你永远不会删除中间包含.如果每个源文件 #include
都包含它直接需要的所有内容,那么您的代码库将会更加健壮.标头守卫可防止这是一种浪费的策略.
However, if your second file itself uses symbols from someLibrary, it's good style to re-include the header. That way you're not "hoping and praying" that you never remove the intermediate include. Your codebase will be more robust if every source file #include
s everything that it directly needs. Header guards prevent this from being a wasteful policy.
相关文章