C ++有一个标准的#include约定吗? [英] Is there a standard #include convention for C++?

查看:96
本文介绍了C ++有一个标准的#include约定吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个相当基本的问题,但它是一个bug了我一会儿。

This is a rather basic question, but it's one that's bugged me for awhile.

我的项目有一堆.cpp(Implementation)和.hpp )文件。

My project has a bunch of .cpp (Implementation) and .hpp (Definition) files.

我发现,当我添加额外的类和更多的类相互依赖,我必须#include其他头文件。一两个星期后,我最终在许多地方的#include指令。后来,我会尝试删除一些#includes,并发现一切仍然有效,因为一些OTHER包含类也包括我刚刚删除的

I find that as I add additional classes and more class inter-dependencies, I have to #include other header files. After a week or two, I end up with #include directives in lots of places. Later, I'll try removing some of the #includes and discover that everything still works because some OTHER included class is also #including what I just removed.

有没有一个简单,容易的规则,把#includes,将阻止这种丑陋的混乱发生在第一个地方?最好的做法是什么?

例如,我曾经在项目中执行.cpp文件只包含相应的Definition .hpp文件,没有其他的。如果还有任何其他.hpp文件需要使用的实现.cpp,它们都被定义.hpp文件引用。

For example, I've worked on projects where the Implementation .cpp file ONLY includes the corresponding Definition .hpp file, and nothing else. If there are any other .hpp files that need to be used by the Implementation .cpp, they are all referenced by the Definition .hpp file.

推荐答案

我总是使用最小耦合的原理。我只包括一个文件,如果当前文件实际需要它;如果我能用一个向前的声明而不是一个完整的定义,我会使用它。我的.cpp文件总是有一堆#includes在顶部。

I always use the principle of least coupling. I only include a file if the current file actually needs it; if I can get away with a forward declaration instead of a full definition, I'll use that instead. My .cpp files always have a pile of #includes at the top.

Bar.h:

class Foo;

class Bar
{
    Foo * m_foo;
};

Bar.cpp:

#include "Foo.h"
#include "Bar.h"

这篇关于C ++有一个标准的#include约定吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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