假设我有一个标题 foo.h:
#ifndef FOO_H
#define FOO_H
#include <string>
#include "non_standard_class.h"
std::string foo(MyClass a);
...
#endif
Run Code Online (Sandbox Code Playgroud)
和实施 foo.cpp将是
#include <vector>
#include "foo.h"
std::string foo(MyClass a)
{
std::vector<int> x;
MyClass b;
...
}
Run Code Online (Sandbox Code Playgroud)
重新包括<string>和non_standard_class.h进入是一个很好的实践foo.cpp吗?关键是:如果我读foo.cpp了,我怎么能理解MyClass来自哪里?我需要看看,foo.h但会更困难.
我遵循的做法:
#include <string>如果std::string在foo.h中有)这种做法的另一种表述:在foo.*中,只包含源代码所需的那些头文件.如果只有foo.cpp需要一个头(但不是foo.h),那么请从foo.cpp中包含它,否则从foo.h中包含它.
所以,在你的情况下,我不会 #include <string>在foo.cpp中,因为它已经包含在foo.h中.
我们假设stringa #include <vector>和foo.h包含std::vector.在这种情况下,我#include <vector>在foo.h中,因为它的源代码需要它 - 并且string已经包含它并不重要.