在构建小型C++项目时,出现以下2个错误,无法找出原因:

  • 错误:在'struct'之后使用typedef-name'TTF_Font'。
    指向以下代码行:Foo.h中的struct TTF_Font;
  • 错误:“TTF_Font”在此处具有先前的声明。
    指向以下代码行:SDL_ttf.h中的typedef struct _TTF_Font TTF_Font;

  • 在新的测试项目中,我将其范围缩小到以下文件:

    Foo.h:
    #ifndef FOO_H
    #define FOO_H
    
    struct TTF_Font;
    
    class Foo
    {
        TTF_Font* font;
    };
    
    #endif // FOO_H
    

    Foo.cpp:
    #include "Foo.h"
    #include "SDL/SDL_ttf.h"
    
    // No implementation, just testing
    

    Main.cpp:
    #include "Foo.h"
    int main(int argc, const char* argv[])
    {
        Foo a;
        return 0;
    }
    

    你们知道我在做什么错吗?

    我的目标是向前声明TTF_Font,因此可以在我的头文件中使用它,而无需包括SDL_ttf头文件。我读到,将头文件包含在其他头文件中是一种不好的做法,因此我改用正向声明。除此单个结构外,我所有其他前向声明都可以正常工作。

    当我用头文件include struct TTF_Font;替换前向声明#include "SDL/SDL.ttf.h"时,它会编译而没有错误。所以我可以使用它,但是我想知道为什么,该死的:-)。

    额外信息:我正在将Code::Blocks IDE与mingw32编译器一起使用。项目使用SDL图形库。还没有多少C++经验,来自C#背景。

    最佳答案

    您正在尝试转发声明某种与实际不同的类型。

    您在声明:

    struct TTF_Font;
    

    当错误消息表明TTF_Font实际上是typedef而不是struct时:
    typedef struct _TTF_Font TTF_Font;
    

    该构造实际上称为_TTF_Font

    您可以多次声明相同的typedef,因此您可以使用typedef声明而不是forward声明来声明struct并介绍typedef,尽管这确实有点像您正在使用要延迟的 header 的实现细节包括。

    关于c++ - 转发声明结构: “has a previous declaration here” 时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4977600/

    10-11 22:58
    查看更多