重写init()方法,Cocos2d-x v2.2

Overriding the init() method , Cocos2d-x v2.2

本文关键字:Cocos2d-x v2 方法 init 重写      更新时间:2023-10-16

我似乎无法在我的类中重写init()方法,这是CCLayer的子类。我能够重写create()方法。所有我需要做的是传递一个int当我创建层的init()方法:下面是create (int n)方法

CCLayer* Stage::create(int n)
{
    CCLayer *pRet = new CCLayer();
    if (pRet && pRet->init(n))
    {
        pRet->autorelease();
        return pRet;
    }
    else
    {
        CC_SAFE_DELETE(pRet);
        return NULL;
    }
}
bool DuneStage::init(int ss)
{
   // this code should execute 
}

.h文件:

virtual bool init(int n);  
static CCLayer* create(int z);

我还需要在cleer .cpp文件中重写此方法吗?

bool CCLayer::init()
{
    bool bRet = false;
    do 
    {        
        CCDirector * pDirector;
        CC_BREAK_IF(!(pDirector = CCDirector::sharedDirector()));
        this->setContentSize(pDirector->getWinSize());
        m_bTouchEnabled = false;
        m_bAccelerometerEnabled = false;
        // success
        bRet = true;
    } while(0);
    return bRet;
}

重写的方法签名必须是父类方法virtual bool init()

如果你想发送参数,那么你可以在你的CCLayer子类中声明它们作为成员变量,然后在create方法中调用init方法之前分配它们。

CCLayer* Stage::create(int n)
{
   CCLayer *pRet = new CCLayer();
   pRet->n = n
   ...........
   ...........
}
Stage* Stage::create(int n)
{
   Stage* pRet = new Stage();
   pRet->n = n
   ...........
   ...........
}