Declare struct in C/C++ enabled style
我都是這樣子 declare structure 的,當然,這樣子的 structure 必須要是單純的struct (ie. POD),不能有 member function 之類 members 存在:
#ifndef __cplusplus
typedef struct LinkList LinkList;
#endif /* __cplusplus */
struct LinkList
{
/* ... */
LinkList* next;
};
這樣一來,我們就可以像 C++ 一樣直接使用 type name 來 declare instances。幾個重點:
- 其實 C++ 也可以
struct Foo或是Foo混著用來 declare instances,不過這樣總是難看了些,所以用上面那招,統一使用 C++ 的方法,包括在 structure 裡面的 member 在內。 - 在 C/C++ 裡,
typedef可以對一個尚未見過的 type name 做 alias,也就是因為如此,在 structure 裡面用 C++ style 來 declare member 才可行。 - 若是
typedef後忘了對應的 structure declaration,那在 declare instances 一樣會產生 compilation error。



Post a Comment