简体   繁体   中英

Including header in the class header and implementation?

I have a class Foo with a corresponding .h and .cpp. Both files make use of an std::string. Should I only #include <string> in the header or include it in both files?

if the header can get away with a forward declaration then I always use that in the header and the #include in the implementation file. (FD can be used for reference and pointer types).

If they both need it, then i tend to put them in both so that if the header is changed I can remove it from the .h.

I include <string> into precompiled header since I don't plan to change it often :). The main rule is: all headers that I won't change often are included into precompiled header: STD, system headers, stable 3rd-party libraries etc. ("often" depends on project size, if project is large "often" tends to "never").

For other headers I voted up @111111's answer

如果你可以更好地使用前向声明,因为你避免多次包含,循环包含等等。所以当你可以使用指针时,放一个前向声明,然后在.cpp中包含你被强制包含的所有其他情况下的文件直接在.h上(当你没有使用指针或引用时以及从类派生时)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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