结构前向声明错误:Typedef使用不同类型重新定义

Struct forward declaration error: Typedef redefinition with different types

本文关键字:新定义 同类型 定义 声明 错误 Typedef 结构      更新时间:2023-10-16

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

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

在cpp文件中,我包含了带有定义的外部标头。。。

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

其中发生错误"不同类型的Typedef重定义('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;

在这种情况下,我不能转发申报吗?

GLFWvidmode不是一个结构,它是一个typedef。不能转发声明typedef。无论是谁选择使用未命名的结构,都做出了糟糕的设计决策。

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

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

注意,数据tagname1tagname2可以相同(您可以在这两个位置使用tagname1tagnameGLFWvidmode)。。现在,由于结构现在有一个标记名(它不再是匿名的),您可以引用它进行正向声明。

yes匿名结构不能用于正向声明,因为没有标记名可引用..:)希望它能有所帮助。