Typedef Structs
將 typedef 與 struct 相結合可以使程式碼更清晰。例如:
typedef struct
{
int x, y;
} Point;
而不是:
struct Point
{
int x, y;
};
可以宣告為:
Point point;
代替:
struct Point point;
更好的是使用以下內容
typedef struct Point Point;
struct Point
{
int x, y;
};
利用 point 的兩種可能定義。如果你首先學習 C++,這樣的宣告是最方便的,如果名稱不明確,你可以省略 struct 關鍵字。
結構的 typedef 名稱可能與程式其他部分的其他識別符號衝突。有些人認為這是一個缺點,但對於大多數擁有 struct 和另一個識別符號的人來說,這是非常令人不安的。臭名昭著的是例如 POSIX’stat
int stat(const char *pathname, struct stat *buf);
你在哪裡看到一個函式 stat,它有一個引數是 struct stat。
typedef’d 沒有標記名稱的結構總是強加整個 struct 宣告對使用它的程式碼是可見的。然後必須將整個 struct 宣告放在標頭檔案中。
考慮:
#include "bar.h"
struct foo
{
bar *aBar;
};
因此,對於沒有標籤名稱的 typedefd struct,bar.h 檔案總是必須包含 bar 的整個定義。如果我們使用
typedef struct bar bar;
在 bar.h 中,可以隱藏 bar 結構的細節。
見 Typedef