.cpp文件而不是.h文件?翻译单位是否受到影响? .h文件和.cpp文件中都需要它,我应该将它包含在.h文件中吗?这有关系吗? stdafx.h)中,例如std和第三方库,这是一个好习惯吗?我自己的文件怎么样,我应该在stdafx.h创建它们的过程中将它们包含在文件中? // myClass.h
#include <string>
// ^-------- should I include it here? --------
class myClass{
myClass();
~myClass();
int calculation()
};
// myClass.cpp
#include "myClass.h"
#include <string>
// ^-------- or maybe here? --------
[..]
int myClass::calculation(){
std::string someString = "Hello World";
return someString.length();
}
// stdafx.h
#include <string.h>
// ^--------- or perhaps here, and then include stdafx.h everywhere? -------
Run Code Online (Sandbox Code Playgroud) 我才刚刚注意到使用String类我的程序,而不包括被编译<string>头.事实证明,<iostream>包括<ios_base>哪些包括<string>.
这是不好的做法,我应该明确包括<string>吗?即使只是一个清晰的案例?
假设这不仅仅适用于<string>标题,这是安全的吗?也许这是特定于实现的,或者标准<string>是否通过<ios_base>和包含标题<iostream>?确保任何受到尊重和广泛使用的实现始终包括<string>提供对<iostream>存在的调用.
假设我们有一个头文件A.h,它依赖于B.h和中声明的内容C.h。B.h也取决于C.h,因此也包括在内。在这种情况下,我们不需要包含C.h进去A.h,没有它就可以编译。
但是我想知道在这些情况下最好的行动方案是什么。如果B.h以某种方式更改并且不再依赖C.h,A.h则会中断。
另一方面,如果我认为到最后,重新包含所有单个依赖关系似乎是不必要/不切实际的。
我常见的情况是标准库。在几乎所有的头文件中,我都必须包含<stdint.h>和<stdbool.h>。我经常跳过它,因为它们已经包含在其中一个依赖项中,但这总是感觉有些武断。