c中測試code
struct Cmstruct { int c; } Cm; // Cm是一個變量 typedef struct MyStruct //這里的 Mystruct 可以省略 { int m; } My; // My 是struct MyStruct 別名 My st; struct Cmstruct cm1; // 只能使用struct Cmstruct來定義 不能使用Cmstruct st.m = 1; printf("%d\n", st.m); // 1 // struct MyStruct st1; 報錯,不能再用此方法,只能 My st1 Cm.c = 10; printf("%d\n", Cm.c); // 10 cm1.c = 22; printf("%d\n", cm1.c); // 22
c++中測試code
struct Mystruct { int m; } cm; // 上面c中說過cm是變量 cm.m = 20; printf("%d\n", cm.m); // 20 struct Mystruct my; // 聲明 my 可以省略 struct,但是c中不可以省略 my.m = 10; printf("%d\n", my.m); // 10 typedef struct Mystruct1 { int s; } Sname; // Sname 是struct Mystruct1 別名 Sname ss; ss.s = 22; printf("%d\n", ss.s); // 22 struct Mystruct1 ss1; // struct Mystruct1中 struct 可以省略 // 這里與C不同,在C中起別名后的struct不能再使用struct Mystruct1聲明 ss1.s = 33; printf("%d\n", ss1.s); // 22
總結:
C與C++相同點
沒有typedef時候cm/Cm是聲明的一個變量,有typedef時候My/Sname 是struct別名。
C與C++不同點
沒有typedef時候,C只能用struct Mystruct來聲明變量,C++中可以省略struct。
有typedef時候,C只能使用別名來聲明變量,C++依然可以使用struct Mystruct或者省略struct。