c++ - 自定义 header 高于标准?

标签 c++ header

将自定义 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/

相关文章:

C++ 对象和线程

c++ - Clang 链接器说符号未定义

PHP - 如何确定 X-Sendfile 是否可用并已安装?

c++ - 如何包含同一 header 的两个不同版本?

c# - 在 ASP.NET 上创建 JSON header

带有标题和 XML 内容的 PHP 发布

c++ - 范围内的随机 float ?

c++ - vxWorks 任务阻塞 shell 命令输入

C++ 将流操纵器复制到其他流

c++ - 为什么将 operator() 的定义从 .h 文件移动到 .cpp 文件导致数据竞争?