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

App*_*ell 0 c++ struct forward-declaration

我想转发声明头文件中的结构.

struct GLFWvidmode;

class DesktopVideoMode {
private:
    const GLFWvidmode *videomode;
public:
    DesktopVideoMode(const GLFWvidmode *videomode);
...
Run Code Online (Sandbox Code Playgroud)

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

#include "DesktopVideoMode.hpp"
#include <GLFW/glfw3.h>
Run Code Online (Sandbox Code Playgroud)

...出现错误" Typedef重新定义不同类型('struct GLFWvidmode'与'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;
Run Code Online (Sandbox Code Playgroud)

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

Igo*_*nik 9

GLFWvidmode不是结构,它是一个typedef.您无法转发声明typedef.选择使用未命名结构的人做出了糟糕的设计决策.


r_g*_*yal 5

我想提一下,这GLFWvidmode是一个匿名结构的typedef名称.如果你有意想转发声明结构,那么你应该总是在结构中添加一个名称标签,同时将结构声明为:

    typedef struct tagname1{
    some members...;
    }tagname2;
Run Code Online (Sandbox Code Playgroud)

注意DAT tagname1并且tagname2可以相同(你可以使用tagname1tagnameGLFWvidmode 在这两个地方)..现在由于结构现在有一个标记名(它不是匿名的了),你可以参考它的向前声明.

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