c++ - 转发声明结构时出错 : "has a previous declaration here"

标签 c++

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

  • 错误:在“结构”之后使用类型定义名称“TTF_Font”。
    指向 Foo.h 中的以下代码行:struct TTF_Font;

  • 错误:“TTF_Font”在此之前有一个声明。
    指向以下代码行:typedef struct _TTF_Font TTF_Font; in SDL_ttf.h。

我已将其缩小到新测试项目中的以下文件:

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

主要.cpp:

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

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

我的目标是转发声明 TTF_Font,这样我就可以在我的头文件中使用它而无需包含 SDL_ttf 头文件。我读到在其他头文件中包含头文件是一种不好的做法,所以我切换到前向声明。除了这个单一结构,我所有其他的前向声明都工作正常。

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

额外信息:我正在使用带有 mingw32 编译器的 Code::Blocks IDE。项目使用 SDL 图形库。尚无太多 C++ 经验,来自 C# 背景。

最佳答案

您正试图将某物转发声明为与实际不同的类型。

您声明:

struct TTF_Font;

当错误消息表明 TTF_Font 实际上是一个 typedef,而不是一个 struct 时:

typedef struct _TTF_Font TTF_Font;

该结构实际​​上称为_TTF_Font

您可以多次声明相同的 typedef,这样您就可以只使用 typedef 声明而不是前向声明来声明 struct 和引入 typedef 虽然感觉有点像您正在使用您试图推迟包含的 header 的实现细节。

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

相关文章:

c++ - 开发 C++ 错误 : expected declaration before '}' token

c++ - 在 C++11 中保存随机数生成器状态

c++ - std::error_code,my_error::check_block == my_error::validate && my_error::accept_block == my_error::validate

c++ - 将 Armadillo 添加到 Qt 项目

C++使截断在运行时打印错误的自动方法

c++ - 如何在C++概念中定义emplace_back和其他可变参数模板函数?

c++ - 函数指针问题

c++ - 哪些设置方法性能更好 : with or without `const&` ?

C++ boost nuget 无法打开文件 Visual Studio 2015

c++ - Xcode 和 wxWidgets 框架