In C++, there are some other things that could be put in the header because, they need, too, be shared:
内联代码
模板
常量(通常是那些您想要使用的内部开关...)
将所有需要共享的内容移到头部,包括共享实现
Does it then mean that there could be sources inside the headers?
是的。事实上,有很多不同的东西可能在一个“头”(即源之间共享)。
转发声明
函数/结构/类/模板的声明/定义
内联代码和模板代码的实现
它变得复杂,在某些情况下(符号之间的循环依赖) ,不可能保持在一个标题。
标题可以分为三个部分
这意味着,在极端情况下,你可以:
一个前向声明
声明/定义标头
实现标头
an implementation source
假设我们有一个模板化的 MyObject,我们可以:
// - - - - MyObject_forward.hpp - - - -
// This header is included by the code which need to know MyObject
// does exist, but nothing more.
template<typename T>
class MyObject ;
.
// - - - - MyObject_declaration.hpp - - - -
// This header is included by the code which need to know how
// MyObject is defined, but nothing more.
#include <MyObject_forward.hpp>
template<typename T>
class MyObject
{
public :
MyObject() ;
// Etc.
} ;
void doSomething() ;
.
// - - - - MyObject_implementation.hpp - - - -
// This header is included by the code which need to see
// the implementation of the methods/functions of MyObject,
// but nothing more.
#include <MyObject_declaration.hpp>
template<typename T>
MyObject<T>::MyObject()
{
doSomething() ;
}
// etc.
.
// - - - - MyObject_source.cpp - - - -
// This source will have implementation that does not need to
// be shared, which, for templated code, usually means nothing...
#include <MyObject_implementation.hpp>
void doSomething()
{
// etc.
} ;
// etc.