【问题标题】:Struct forward declaration error: Typedef redefinition with different types结构前向声明错误:使用不同类型重新定义Typedef
【发布时间】:2013-08-29 03:52:18
【问题描述】:

我想在头文件中转发声明一个结构体。

struct GLFWvidmode;

class DesktopVideoMode {
private:
    const GLFWvidmode *videomode;
public:
    DesktopVideoMode(const GLFWvidmode *videomode);
...

在 cpp 文件中,我在定义中包含了外部标头...

#include "DesktopVideoMode.hpp"
#include <GLFW/glfw3.h>

...发生错误“Typedef redefinition with different types ('struct GLFWvidmode' vs 'GLFWvidmode')”:

typedef struct
{
    /*! The width, in screen coordinates, of the video mode.
     */
    int width;
    /*! The height, in screen coordinates, of the video mode.
     */
    int height;
    /*! The bit depth of the red channel of the video mode.
     */
    int redBits;
    /*! The bit depth of the green channel of the video mode.
     */
    int greenBits;
    /*! The bit depth of the blue channel of the video mode.
     */
    int blueBits;
    /*! The refresh rate, in Hz, of the video mode.
     */
    int refreshRate;
} GLFWvidmode;

在这种情况下我不能转发声明吗?

【问题讨论】:

  • 是的,我意识到,在我发布评论并删除它之后。
  • @AdamS: 那么你不能避免包括标题...

标签: c++ struct forward-declaration


【解决方案1】:

GLFWvidmode 不是结构,它是 typedef。您不能前向声明 typedef。选择使用未命名结构的人做出了糟糕的设计决定。

【讨论】:

  • 我能够更改外部标头,因此所有出现的 typedef 结构都是合法结构,感谢您的提示。
【解决方案2】:

我想提一下 GLFWvidmode 是匿名结构的 typedef 名称。如果您有意转发声明该结构,那么您应该始终在将结构声明为时向该结构添加一个名称标签:

    typedef struct tagname1{
    some members...;
    }tagname2;

注意 dat tagname1tagname2 可以相同(您可以在这两个地方使用 tagname1tagnameGLFWvidmode).. 现在因为结构现在有一个标记名(它不是匿名了)你可以参考它进行前向声明。

并且是的匿名结构不能用于前向声明,因为没有可以引用的标记名.. :) 希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多