typdef union { int n; char c; } NC; nc.c 確實有 *(char *)&nc 的意思 nc.n 確實有 *(int *)&nc 的意思 (存取方式) 我覺得,,可以用union去描述同一概念,,但不會同時出現(xiàn)的東西,。 比如 union mark { int score; char grade; } 寫程序時,,別人比較容易理解,;改的時候也容易,。 The primary usefulness of a union is to conserve space, since it provides a way of letting many different types be stored in the same space. Unions also provide crude polymorphism. However, there is no checking of types, so it is up to the programmer to be sure that the proper fields are accessed in different contexts. The relevant field of a union variable is typically determined by the state of other variables, possibly in an enclosing struct. (union常不是單獨使用,,而是與struct一起,它的值常是由密封在struct中的其他變量的狀態(tài)決定的) 舉個例子: [php] struct in6_addr { union { uint8_t u6_addr8[16]; uint16_t u6_addr16[8]; uint32_t u6_addr32[4]; } in6_u; #define s6_addr in6_u.u6_addr8 #define s6_addr16 in6_u.u6_addr16 #define s6_addr32 in6_u.u6_addr32 }; [/php] uinion在協(xié)議里用的很多 |
|