c语言中的typedef struct相当于java的一个类?,C ++中'struct'和'typedef struct'之间的区别?...
在C ++中,之間有什么區(qū)別:
struct Foo { ... };
和
typedef struct { ... } Foo;
#1樓
您不能對typedef結(jié)構(gòu)使用forward聲明。
struct本身是一個匿名類型,因此您沒有實際名稱來轉(zhuǎn)發(fā)聲明。
typedef struct{
int one;
int two;
}myStruct;
像這樣的前瞻聲明不會起作用:
struct myStruct; //forward declaration fails
void blah(myStruct* pStruct);
//error C2371: 'myStruct' : redefinition; different basic types
#2樓
C ++中'typedef struct'和'struct'之間的一個重要區(qū)別是'typedef structs'中的內(nèi)聯(lián)成員初始化將不起作用。
// 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是創(chuàng)建數(shù)據(jù)類型。 typedef用于設(shè)置數(shù)據(jù)類型的昵稱。
#4樓
C ++沒有區(qū)別,但是我相信它會允許你在不明確地執(zhí)行的情況下聲明struct Foo的實例:
struct Foo bar;
#5樓
在C ++中,只有一個微妙的區(qū)別。 這是C的延續(xù),它有所作為。
C語言標準( C89§3.1.2.3 , C99§6.2.3和C11§6.2.3 )要求為不同類別的標識符分別命名空間,包括標記標識符 (用于struct / union / enum )和普通標識符 (用于typedef和其他標識符)。
如果你剛才說:
struct Foo { ... };
Foo x;
您會收到編譯器錯誤,因為Foo僅在標記名稱空間中定義。
您必須將其聲明為:
struct Foo x;
每當你想要引用Foo ,你總是要把它稱為struct Foo 。 這會很快煩人,所以你可以添加一個typedef :
struct Foo { ... };
typedef struct Foo Foo;
現(xiàn)在struct Foo (在標記命名空間中)和普通Foo (在普通標識符命名空間中)都引用相同的東西,并且您可以在沒有struct關(guān)鍵字的情況下自由聲明Foo類型的對象。
構(gòu)造:
typedef struct Foo { ... } Foo;
只是聲明和typedef的縮寫。
最后,
typedef struct { ... } Foo;
聲明一個匿名結(jié)構(gòu)并為其創(chuàng)建一個typedef 。 因此,使用此構(gòu)造,它在標記名稱空間中沒有名稱,只有typedef名稱空間中的名稱。 這意味著它也無法向前宣布。 如果要進行前向聲明,則必須在標記名稱空間中為其指定名稱 。
在C ++中,所有struct / union / enum / class聲明都像隱式typedef一樣,只要該名稱不被另一個具有相同名稱的聲明隱藏。 有關(guān)詳細信息,請參閱Michael Burr的答案 。
總結(jié)
以上是生活随笔為你收集整理的c语言中的typedef struct相当于java的一个类?,C ++中'struct'和'typedef struct'之间的区别?...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎么买etf
- 下一篇: 算法训练 猴子分苹果c语言,算法训练 猴