聲明:這不是一個技術性的,而是一個實際的答案。有關技術問題,請參閱其他答案。這個答案讀取的是自以爲是和主觀的,但請在我試圖解釋更大的圖片時忍受。
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