声明:这不是一个技术性的,而是一个实际的答案。有关技术问题,请参阅其他答案。这个答案读取的是自以为是和主观的,但请在我试图解释更大的图片时忍受。
struct
是一个奇怪的野兽,因为你的右括号}
和分号;
之间放的东西是指里面的内容还是那些括号之前。我知道这是为什么,和语法也有一定道理,但我个人觉得非常反直觉的大括号通常是指范围:
反直观的例子:
// declares a variable named `foo` of unnamed struct type.
struct {
int x, y;
} foo;
foo.x = 1;
// declares a type named `Foo` of unnamed struct type
struct {
int x, y;
} typedef Foo;
Foo foo2;
foo2.x = 2;
// declares a type named `Baz` of the struct named `Bar`
struct Bar {
int x, y;
} typedef Baz;
// note the 'struct' keyword to actually use the type 'Bar'
struct Bar bar;
bar.x = 3;
Baz baz;
baz.x = 4;
有这么如果以这种方式使用,可能会出现许多细微的问题,如密码语法struct
和typedef
。如下所示,非常容易声明一个变量而不是偶然类型。编译器只有有限的帮助,因为几乎所有的组合都是语法正确的。他们并不一定表示你想表达的内容。这是一个pit of despair。
错误示例:
// mixed up variable and type declaration
struct foo {
int x, y;
} Foo;
// declares a type 'foo' instead of a variable
typedef struct Foo {
int x, y;
} foo;
// useless typedef but compiles fine
typedef struct Foo {
int x, y;
};
// compiler error
typedef Foo struct {
int x, y;
};
出于可读性和维护的原因,我更喜欢单独声明一切,从不把右花括号后面的东西。直观的语法轻易超过额外代码行的成本。我认为这种做法makes it easy to do the right things and annoying to do the wrong things。
直观的例子:
// declares a struct named 'TVector2'
struct TVector2 {
float x, y;
};
// declares a type named 'Vector2' to get rid of the 'struct' keyword
// note that I really never use 'TVector2' afterwards
typedef struct TVector2 Vector2;
Vector2 v, w;
v.x = 0;
v.y = 1;
难道不应该永远是 “typedef的”?这是结构的特殊扩展吗? –
Itaypk
@Itaypk不仅仅是结构体,你可以从你的'enum'例子中看到。 –
@Itaypk;不是。它不是扩展名。查看编辑。 – haccks