从其他头文件实现结构

Implementing structure from other header file

本文关键字:实现 结构 文件 其他      更新时间:2023-10-16

我必须在类头中有一个结构"configset",类似于以下内容:

class A {
public:
    static configset *getnext();
}

当然,编译器抱怨configset不是一个类型,但它是在另一个头文件中实现的,还有一些函数。正因为如此,我不能只包含那个头文件,编译器会抛出这些函数被多次定义的错误。但是我怎样才能在类头中获得配置集呢?仅仅复制也不起作用,因为编译器会抛出一个错误,即结构被定义了两次。

转发声明configset或将头文件中定义的函数声明为inline

使用转发声明,如下所示:

// Forward declare configset. Tells compiler that the class/struct is defined in 
// another translation unit
struct configset;
class A {
public:
    static configset *getnext();
};

请注意,只有当您只使用指向configset的指针时,这才有效。

configset方法的实现移动到一个单独的.cpp(而不是头)文件中。