在看 cocos2d-x 的源码,发现很多地方有这样的定义(源码在 这里 ):
typedef struct _AsyncStruct{ std::string filename; CCObject *target; SEL_CallFuncO selector; int handler;} AsyncStruct;
我的问题是:为什么不直接这样写:
struct AsyncStruct{ std::string filename; CCObject *target; SEL_CallFuncO selector; int handler;}
解决方案
C语言规定,变量定义要写elaborated type
,也就是说,对于struct S{...}
类型的变量定义要写成struct S s;
,为了省掉这个struct
,你就需要用typedef struct S S1
来定义个名叫S1
的elaborated type
,然后你就可以直接用S1
来定义变量了。
其实C标准中S
和S1
可以重名,也就是说你可以写typedef struct S S
,但有一些古老的编译器不支持你这么写,所以一般会换个名字比如typedef struct _S S
。
以上所述只针对C语言,C++基本没这个问题(除了friend声明)。
PS. 对于像cocos2d-x这样只能用在新编译器上的C++库,还这么写只能说明作者其实根本没明白为什么。