以下代码不编译 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'之间的区别?
这是GCC中的一个错误
参考: - 错误46206 - 使用typedef-name错误,其中typedef名称隐藏结构名称
G ++拒绝以下代码:
Run Code Online (Sandbox Code Playgroud)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; } };此行为可在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中得到修复