C / C ++中的自足头文件 [英] Self-sufficient header files in C/C++

查看:128
本文介绍了C / C ++中的自足头文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发布了一个问题,询问什么操作会构成 禅C ++ 。我收到了很好的答案,但我不明白一个建议:

I recently posted a question asking for what actions would constitute the Zen of C++. I received excellent answers, but I could not understand one recommendation:


  • 使头文件自给自足

如何确保您的头文件自给自足

How do you ensure your header files are self-sufficient?

编辑:我发现

I found this question which addresses the "Best Practices" part of mine.

推荐答案

自足的头文件不依赖于包含在其中的正确工作的上下文。如果你确保你在使用它之前#include或定义/声明一切,你自己就是一个自给自足的头。

一个自足头的例子可能是东西像这样:

A self sufficient header file is one that doesn't depend on the context of where it is included to work correctly. If you make sure you #include or define/declare everything before you use it, you have yourself a self sufficient header.
An example of a non self sufficient header might be something like this:

----- MyClass.h -----

class MyClass
{
   MyClass(std::string s);
};

-

---- MyClass.cpp -----

#include <string>
#include "MyClass.h"

MyClass::MyClass(std::string s)
{}

在此示例中,MyClass.h使用std :: string,而不包含#include。
为了这个工作,在MyClass.cpp你需要把#include之前#includeMyClass.h。

如果MyClass的用户没有这样做,他会得到一个错误std :: string不包括在内。

In this example, MyClass.h uses std::string without first #including . For this to work, in MyClass.cpp you need to put the #include before #include "MyClass.h".
If MyClass's user fails to do this he will get an error that std::string is not included.

维护您的页眉是自给自足的,通常可以忽略。例如,你有一个巨大的MyClass头,你添加到另一个使用std :: string的小方法。在所有的地方,这个类目前使用,已经#include在MyClass.h之前。然后有一天你#include MyClass.h作为第一个标题,突然你有一个文件,你甚至没有触摸(MyClass.h)所有这些新的错误

小心保持标题是自足的帮助以避免此问题。

Maintaining your headers to be self sufficient can be often neglected. For instance, you have a huge MyClass header and you add to it another small method which uses std::string. In all of the places this class is currently used, is already #included before MyClass.h. then someday you #include MyClass.h as the first header and suddenly you have all these new error in a file you didn't even touch (MyClass.h)
Carefully maintaining your headers to be self sufficient help to avoid this problem.

这篇关于C / C ++中的自足头文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆