【问题标题】:why #include only complete declarations and definitions?为什么#include 只包含完整的声明和定义?
【发布时间】:2018-11-16 16:43:19
【问题描述】:

先生。 Bjarne Stroustrup 在他的书“C++ 编程语言第四版”第 425 页中间(第 15.2.2 节)中说:

明智的做法是不要对#include 的使用过于聪明。我的建议是: ... 只包括完整的声明和定义。

我不明白他是什么意思? 我看到很多代码使用 .h 文件进行声明,使用 .cpp 文件进行定义,然后只包含 .h 文件。 那么他所说的推荐究竟是什么意思呢?

【问题讨论】:

  • 结构和类是定义的,通常在头文件中。通常是模板和内联函数。

标签: c++ header-files declaration definition


【解决方案1】:

如果我正确理解 Stroustrup,这些是“完整的”声明:

// foo.h
void foo();
struct S {
    int bar() const;
};

这些是“不完整”的声明,你不应该写这样的标题:

// bar_start.h
struct Bar {

// bar_end.h
};

做:

#include "foo.h"

不要:

#include "bar_start.h"
void foo();  // foo is a member of Bar
#include "bar_end.h"

【讨论】:

  • @user463035818 标题应该包含在内,所以我看不出有什么区别。
  • 我真的很难想象为什么要编写这样糟糕的代码。对我来说,你不应该这样做似乎很明显,所以我也被这句话弄糊涂了。
【解决方案2】:

我通过本书作者 (Bjarne Stroustrup) 的电子邮件提出了这个问题,以确认他的意思。 他回应:

考虑:

#define X foo
#include "essentials.h"

// ... the rest goes here

};

essentials.h 在哪里

class X {

    X();

    X(const X& a);

    X(X&&);

    // ... and more ...

这种“聪明”的结果是,将定义分散到多个文件中会导致无法维护的混乱。

【讨论】:

    猜你喜欢
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 2013-11-11
    • 2010-11-27
    相关资源
    最近更新 更多