将自定义 header 放在 include
部分比标准 header 更高的位置是否合理?
例如在 someclass.hpp
中包含部分:
#include "someclass.h"
#include "global.h"
#include <iostream>
#include <string>
这是最佳实践吗?如果是,利润是多少?
最佳答案
原因是,如果您忘记在 someclass.h
中包含依赖 header ,那么无论实现文件将其作为第一个 header 包含,都会收到未定义或未声明类型的警告/错误,什么的。如果您首先包含其他 header ,那么您可能会掩盖这一事实 - 假设包含的 header 定义了所需的类型、函数等。示例:
我的类型.h:
// Supressed include guards, etc
typedef float my_type;
一些类.h:
// Supressed include guards, etc
class SomeClass {
public:
my_type value;
};
一些类.cpp:
#include "my_type.h" // Contains definition for my_type.
#include "someclass.h" // Will compile because my_type is defined.
...
这将编译正常。但是假设您想在程序中使用 SomeClass
。如果在包含 someclass.h
之前不包含 my_type.h
,您将收到一个编译器错误,指出 my_type
未定义。示例:
#include "someclass.h"
int main() {
SomeClass obj;
obj.value = 1.0;
}
关于c++ - 自定义 header 高于标准?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9373941/