简体   繁体   English

在header或cpp中包含std库?

[英]Include std library in header or cpp?

如果我有一个使用iostream的A类,我应该把iostream的include语句放在Ah或A.cpp中吗?

This is an area of some controversy. 这是一个有争议的领域。 My own preference is that each header should be able to stand alone, so if it needs other headers, it includes them. 我自己的偏好是每个标题应该能够独立,所以如果它需要其他标题,它包括它们。 In other words, if client code is going to need to include <iostream> (or whatever) anyway, your header should handle that for them. 换句话说,如果客户端代码无论如何都需要包含<iostream> (或其他),那么你的标题应该为它们处理。 OTOH, if the user of the iostream is strictly hidden so the client code doesn't need to include it at all, then it should only be included in the implementation file. OTOH,如果iostream的用户被严格隐藏,因此客户端代码根本不需要包含它,那么它应该只包含在实现文件中。

In many cases (especially where the header is open to frequent change), you'd prefer to avoid including it in the header. 在许多情况下(特别是在标题对频繁更改开放的情况下),您宁愿避免将其包含在标题中。 In such cases, the PImpl idiom can be useful to get the dependency out of the header. 在这种情况下,PImpl习惯用法可以用于从头部获取依赖性。

If you do need to include <iostream> , do your clients a favor and consider whether you can #include <iosfwd> instead of <iostream> though. 如果您确实需要包含<iostream> ,请帮助您的客户,并考虑是否可以#include <iosfwd>而不是<iostream> This can improve compile time a fair amount. 这可以大大改善编译时间。

Include it where its needed. 将其包括在需要的地方。 If you use something defined in <iostream> in the declaration of the class (like a member variable, a member function parameter or return type, etc), then it should be in the H file. 如果你在类的声明中使用<iostream>中定义的东西(比如成员变量,成员函数参数或返回类型等),那么它应该在H文件中。 If you only use it in the implementation - then in the CPP. 如果您只在实施中使用它 - 那么在CPP中。

Include it in the cpp. 将它包含在cpp中。 That way it's not potentially included in other cpp files that may include your Ah but don't need the iostream. 这样它就不会包含在其他cpp文件中,这些文件可能包含你的Ah但不需要iostream。 Unless of course for some reason there is something in your header file that needs iostream. 除非由于某种原因,你的头文件中有一些东西需要iostream。 But if that's the case you might be doing something else wrong... 但如果是这样的话,你可能会做错其他的事......

It depends. 这取决于。

If you use the classes in the header file, you need it in the header file (obviously). 如果您使用头文件中的类,则需要在头文件中(显然)。

If you just use the class declarations you can use incomplete types. 如果您只使用类声明,则可以使用不完整的类型。 In that case, include <iosfwd> in your header file, and <iostream> in the cpp 在这种情况下,在头文件中包含<iosfwd> ,在cpp中包含<iostream>

Use it where it is needed. 在需要的地方使用它。

If your class declaration references types in the header, you will need to include it there. 如果您的类声明引用标题中的类型,则需要将其包含在那里。 If it's only in the implementation, then you can include it in the cpp file. 如果它只在实现中,那么您可以将它包含在cpp文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM