首页 > 解决方案 > 将类声明与定义分开

问题描述

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

foo.hpp文件具有Foo带有其描述的类声明,并且该文件还包括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's 的方法编写评论,foo.hpp使其看起来像这样:

/* 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'.

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

标签: c++classdeclaration

解决方案


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

// .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 */
}

推荐阅读