将 class 声明与定义分开

Separate class declaration from definition

我想将 class 定义和声明分成 2 个单独的文件:foo.hppfoo.inl

foo.hpp 文件有 Foo class 声明及其描述,该文件还包括 foo.inl:

/* foo.hpp */

// Foo class description comment
class Foo;

#include "foo.inl"

foo.inl 包含 Foo 定义,没有任何代码描述注释。

/* foo.inl */

class Foo {
    Foo() = default;

    void bar() {
        /* do something */
    }
}

我正在尝试为 foo.hppFoo 的方法撰写评论,使其看起来像这样:

/* foo.hpp */

// Foo class description comment
class Foo;

// This is my default constructor
Foo::Foo();

// This is my very helpful function
Foo::bar();

#include "foo.inl"

但是编译器给出了一个可以理解的错误:invalid use of incomplete type 'class Foo'.

那么有什么办法可以这样声明函数并为它们写注释吗?

Foo::Foo();void Foo::bar(); 区域成员函数声明,并且不允许在 class.

之外

你有点落后了,在“主”头文件foo.hpp中定义class。然后在“内联”头文件 foo.inl.

中将函数定义为 inline

也许是这样的:

// Foo.hpp
#pragma once

class Foo
{
public:
    // The default constructor
    Foo();

    // This is my very helpful function
    void bar();
};

#include "Foo.inl"

然后内联文件:

// Foo.inl
#pragma once

inline Foo::Foo()
{
}

inline void Foo::bar()
{
}

如果内联函数足够简单,请将它们放在主头文件 Foo.hppFoo class 定义中。如果它们太复杂而不能真正内联,请将它们放在一个单独的源文件中 Foo.cpp 以与您的应用程序一起构建(但 包含在 #include 中).

如果要拆分 class 方法的定义和声明,则必须定义 class:

// .h

// That is my class Foo
class Foo {
    // Constructor
    Foo();

    // This is my very helpful function
    void bar();
};

// cpp
Foo::Foo() = default;

void Foo::bar() {
    /* do something */
}