【发布时间】:2017-03-27 09:47:01
【问题描述】:
我编写了以下简单程序并在 gcc 编译器上编译了它
#include <stdio.h>
typedef int i;
void foo()
{
struct i {i i;} i;
i.i = 3;
printf("%i\n", i.i);
}
int main() { foo(); }
它在 C 中编译和运行良好。(参见现场演示 here)但在 C++ 中编译失败。 C++ 编译器给出以下错误信息。
prog.cc: In function 'void foo()':
prog.cc:5:17: error: field 'i' has incomplete type 'foo()::i'
struct i {i i;} i;
^
prog.cc:5:12: note: definition of 'struct foo()::i' is not complete until the closing brace
struct i {i i;} i;
观看现场演示here
我在 C 和 C++ 标准中找不到与此相关的规则。为什么它在 C 中编译得很好,但在 C++ 中编译得不好?标准对此有何规定?我非常清楚 C 和 C++ 是具有不同规则的不同语言,但我很想知道确切的规则。
【问题讨论】:
-
我想问题在于,在 C 中,您的结构名称是
struct i,因此您的结构中的i明确具有typedef int i;的类型,即int,但在 C++ 中structs name 只是i所以你的structs name 阴影(阴影甚至发生在typenames 上?)typedef 和你的struct 包含它自己。 -
如果你的风格是这样的,要拥有同名的变量、类型和结构,我建议你参加International Obfuscated C Code Contest。否则这将不是问题。
-
你的程序听起来像说我的骑士。“我!我!我!”
标签: c++ c struct language-lawyer