#include 如何在 C++ 中工作? [英] How does #include work in C++?

查看:33
本文介绍了#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?

推荐答案

不,#includes 是可传递的.

但是,如果您的第二个文件本身使用 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 #includes everything that it directly needs. Header guards prevent this from being a wasteful policy.

这篇关于#include 如何在 C++ 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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