为什么只包含完整的声明和定义?

时间:2018-11-16 16:43:19

标签: c++ header-files declaration definition

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

  

明智的是,不要对#include的使用过于机灵。我的建议是:   ...   仅包含完整的声明和定义。

我不明白他是什么意思? 我看到很多代码,这些代码使用.h文件进行声明,并使用.cpp文件进行定义,然后仅包含.h文件。 那么他的建议到底是什么意思?

2 个答案:

答案 0 :(得分:2)

如果我正确理解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"

答案 1 :(得分:1)

我通过这本书的作者(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 ...
  

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