C ++中'struct'和'typedef struct'之間的區別?

在C ++中,之間有什麼區別: this

struct Foo { ... };

spa

typedef struct { ... } Foo;

#1樓

您不能對typedef結構使用forward聲明。 code

struct自己是一個匿名類型,所以您沒有實際名稱來轉發聲明。 對象

typedef struct{
    int one;
    int two;
}myStruct;

像這樣的前瞻聲明不會起做用: get

struct myStruct; //forward declaration fails

void blah(myStruct* pStruct);

//error C2371: 'myStruct' : redefinition; different basic types

#2樓

C ++中'typedef struct'和'struct'之間的一個重要區別是'typedef structs'中的內聯成員初始化將不起做用。 編譯器

// the 'x' in this struct will NOT be initialised to zero
typedef struct { int x = 0; } Foo;

// the 'x' in this struct WILL be initialised to zero
struct Foo { int x = 0; };

#3樓

Struct是建立數據類型。 typedef用於設置數據類型的暱稱。 it


#4樓

C ++沒有區別,可是我相信它會容許你在不明確地執行的狀況下聲明struct Foo的實例: io

struct Foo bar;

#5樓

在C ++中,只有一個微妙的區別。 這是C的延續,它有所做爲。 編譯

C語言標準( C89§3.1.2.3C99§6.2.3C11§6.2.3 )要求爲不一樣類別的標識符分別命名空間,包括標記標識符 (用於struct / union / enum )和普通標識符 (用於typedef和其餘標識符)。 class

若是你剛纔說:

struct Foo { ... };
Foo x;

您會收到編譯器錯誤,由於Foo僅在標記名稱空間中定義。

您必須將其聲明爲:

struct Foo x;

每當你想要引用Foo ,你老是要把它稱爲struct Foo 。 這會很快煩人,因此你能夠添加一個typedef

struct Foo { ... };
typedef struct Foo Foo;

如今struct Foo (在標記命名空間中)和普通Foo (在普通標識符命名空間中)都引用相同的東西,而且您能夠在沒有struct關鍵字的狀況下自由聲明Foo類型的對象。


構造:

typedef struct Foo { ... } Foo;

只是聲明和typedef的縮寫。


最後,

typedef struct { ... } Foo;

聲明一個匿名結構併爲其建立一個typedef 。 所以,使用此構造,它在標記名稱空間中沒有名稱,只有typedef名稱空間中的名稱。 這意味着它也沒法向前宣佈。 若是要進行前向聲明,則必須在標記名稱空間中爲其指定名稱


在C ++中,全部struct / union / enum / class聲明都像隱式typedef同樣,只要該名稱不被另外一個具備相同名稱的聲明隱藏。 有關詳細信息,請參閱Michael Burr的答案

相關文章
相關標籤/搜索