对cocos有了解的人,都应该对CREATE_FUNC这个宏不陌生,
那么今天寒風为大家解析一下这个函数。
首先我们看看里边的源代码:
- <span style="font-family:SimHei;">/**
- * define a create function for a specific type,such as CCLayer
- * @__TYPE__ class type to add create(),such as CCLayer
- */
- #define CREATE_FUNC(__TYPE__) \
- static __TYPE__* create() \
- { \
- __TYPE__ *pRet = new __TYPE__(); \
- if (pRet && pRet->init()) \
- { \
- pRet->autorelease(); \
- return pRet; \
- } \
- else \
- { \
- delete pRet; \
- pRet = NULL; \
- return NULL; \
- } \
- } </span>
下边是我做的一款贪吃蛇的游戏,代码如下:
- <span style="font-family:SimHei;">/**
- * define a create function for a specific type,such as CCLayer
- * @__TYPE__ class type to add create(),such as CCLayer
- */
- #define CREATE_FUNC(__TYPE__) \
- static __TYPE__* create() \
- { \
- __TYPE__ *pRet = new __TYPE__(); \
- if (pRet && pRet->init()) \
- { \
- pRet->autorelease(); \
- return pRet; \
- } \
- else \
- { \
- delete pRet; \
- pRet = NULL; \
- return NULL; \
- } \
- } </span>
- SnakeBody*SnakeBody::create(int type)
- {
-
- SnakeBody *pRet = new SnakeBody();
- if (pRet && pRet->init(type))
- {
- pRet->autorelease();
- return pRet;
- }
- else
- {
- delete pRet;
- pRet = NULL;
- return NULL;
- }
- }
我们可以看到在宏的下面定义了一个create()函数返回的类型就是宏带入参
- SnakeBody*SnakeBody::create(int type)
- {
- SnakeBody *pRet = new SnakeBody();
- if (pRet && pRet->init(type))
- {
- pRet->autorelease();
- return pRet;
- }
- else
- {
- delete pRet;
- pRet = NULL;
- return NULL;
- }
- }