勤奋努力,持之以恒!
cocos2d-x定义了很多宏定义,有助于我们提高开发效率
而CC_PROPERTY 用来声明一个protected变量。
使用CC_PROPERTY声明的变量可以使用getter获取变量的值,使用setter设置变量的值。
CC_PROPERTY的声明在CCPlatformMacros.h中,结构如下
/** CC_PROPERTY is used to declare a protected variable.
We can use getter to read the variable, and use the setter to change the variable.
@param varType : the type of variable. 变量类型
@param varName : variable name. 变量名称
@param funName : "get + funName" is the name of the getter.
"set + funName" is the name of the setter.
@warning : The getter and setter are public virtual functions, you should rewrite them first.
The variables and methods declared after CC_PROPERTY are all public.
If you need protected or private, please declare.
*/
#define CC_PROPERTY(varType, varName, funName)\
protected: varType varName;\
public: virtual varType get##funName(void);\
public: virtual void set##funName(varType var);
CC_PROPERTY使用方法:
.h
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
USING_NS_CC;
using namespace std;
class HelloWorld : public CCLayer
{
public:
virtual bool init();
static CCScene* scene();
CREATE_FUNC(HelloWorld);
CC_PROPERTY(unsigned int, _heroID, HeroID);
CC_PROPERTY(string, _heroName, HeroName);
};
#endif // __HELLOWORLD_SCENE_H__
.cpp
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
using namespace cocos2d;
using namespace CocosDenshion;
CCScene* HelloWorld::scene()
{
CCScene *scene = CCScene::create();
HelloWorld *layer = HelloWorld::create();
scene->addChild(layer);
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
if ( !CCLayer::init() )
{
return false;
}
this->setHeroID(110120);
this->setHeroName("police doctor");
CCLog("HeroID == %d, HeroName == %s",this->getHeroID(),this->getHeroName().c_str());
return true;
}
//CC_PROPERTY(unsigned int, _heroID, HeroID);
void HelloWorld::setHeroID(unsigned int var)
{
_heroID = var;
}
unsigned int HelloWorld::getHeroID()
{
return _heroID;
}
//CC_PROPERTY(string, _heroName, HeroName);
void HelloWorld::setHeroName(string var)
{
_heroName = var;
}
string HelloWorld::getHeroName()
{
return _heroName;
}