在标头或 cpp 中包含 std 库?
如果我有一个使用iostream的A类,我应该将iostream的include语句放在Ah还是A.cpp中?
If I have a class A which uses iostream, should I put the include statement of iostream in A.h or A.cpp?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一个存在争议的领域。我自己的偏好是每个标头应该能够独立,因此如果需要其他标头,它会包含它们。换句话说,如果客户端代码无论如何都需要包含
(或其他内容),您的标头应该为它们处理该问题。 OTOH,如果 iostream 的用户被严格隐藏,因此客户端代码根本不需要包含它,那么它应该只包含在实现文件中。在许多情况下(尤其是标头可以频繁更改的情况),您希望避免将其包含在标头中。在这种情况下,PImpl 习惯用法对于从标头中获取依赖项很有用。
如果您确实需要包含不过。这可以大大缩短编译时间。
,请帮您的客户考虑一下是否可以#include
而不是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. 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.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.
If you do need to include
<iostream>
, do your clients a favor and consider whether you can#include <iosfwd>
instead of<iostream>
though. This can improve compile time a fair amount.将其包含在需要的地方。如果您在类声明中使用
中定义的内容(例如成员变量、成员函数参数或返回类型等),那么它应该位于 H 文件中。如果您只在实现中使用它 - 那么在 CPP 中。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. If you only use it in the implementation - then in the CPP.将其包含在cpp中。这样,它就不会包含在可能包含您的 Ah 但不需要 iostream 的其他 cpp 文件中。当然,除非由于某种原因你的头文件中有一些东西需要 iostream。但如果是这样的话,你可能做错了什么......
Include it in the cpp. That way it's not potentially included in other cpp files that may include your A.h but don't need the iostream. Unless of course for some reason there is something in your header file that needs iostream. But if that's the case you might be doing something else wrong...
在需要的地方使用它。
如果您的类声明引用标头中的类型,则需要将其包含在那里。如果只是在实现中,那么您可以将其包含在 cpp 文件中。
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 中包含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