删除变量时C++奇怪的编译错误

P0W*_*P0W 9 c++

以下代码不编译 g ++ 4.8.1

struct Layers
{
    typedef struct Widgets { } Widgets;

    virtual void fun(void) 
    {
        struct Widgets w;
    }

    Widgets w, x, y, z ;
};
Run Code Online (Sandbox Code Playgroud)

但是,如果我只是使用Widgets w, x, y ; //Remove variable z编译!

为什么会这样?我在这里错过了什么?

小智 7

那是因为你typedef是结构Widgets,检查错误:

error: using typedef-name 'Layers::Widgets' after 'struct'

因此,解决方法是删除struct函数中的.总结为:

struct Layers
{
    typedef struct Widgets { } Widgets;

    virtual void fun(void) 
    {
        Widgets w;
    }

    Widgets w, x, y, z ;
};

int main() { }
Run Code Online (Sandbox Code Playgroud)

在这里阅读更多相关内容:C++中'struct'和'typedef struct'之间的区别?

  • 这并不能解释为什么删除`,z'会使代码编译 (6认同)

P0W*_*P0W 7

这是GCC中的一个错误

参考: - 错误46206 - 使用typedef-name错误,其中typedef名称隐藏结构名称

G ++拒绝以下代码:

class Foo
{
    bool a, b, c, d;
    typedef struct Bar { } Bar;
    virtual void foo(void) {
        struct Bar bar;
    }
};    
example.cc: In member function ‘virtual void Foo::foo()’:
example.cc:6: error: using typedef-name ‘Foo::Bar’ after ‘struct’
example.cc:4: error: ‘Foo::Bar’ has a previous declaration here
example.cc:6: error: invalid type in declaration before ‘;’ token
Run Code Online (Sandbox Code Playgroud)

但接受许多类似的例子,包括:

class Foo
{
    bool a, b, c;
    typedef struct Bar { } Bar;
    virtual void foo(void) {
        struct Bar bar;
    }
};
Run Code Online (Sandbox Code Playgroud)

此行为可在x86_64-redhat-linux(4.1.2和4.4.0)和i386-pc-solaris2.11(4.2.4,4.3.4和4.5.1)上重现

我不确定这是否严格合法或不符合标准,但接受其中一种情况似乎没有意义,而不是其他情况......

这似乎在最新的GCC 4.9.0中得到修复

  • 大声笑,有一个像你的例子.这可能是培养声誉的好方法:D (2认同)