Search code examples
c++ioscocos2d-x

How to specify argument in CREATE_FUNC in Coco2d-x


My MessageBoxes class has an argument passed in the constructor, I hope to know how can I specify the argument, which is std::string _content in this context, in the CREATE_FUNC()?

The error I get says "constructors cannot be declared 'static'"

This is the code of MessageBoxes.h:

class MessageBoxes : public cocos2d::Node
{
    private:
        Sprite* _sprite;
        bool _speaking;
        float _speakingTime;
        std::string _content;
    public:
        CREATE_FUNC(MessageBoxes(std::string content)); 

    protected:
        virtual bool init(std::string _content);
        void setSprite();
        void setContent();
};

Solution

  • CREATE_FUNC is a predefined macros defined in CCPlatformMacros.h

    #define CREATE_FUNC(__TYPE__) \
    static __TYPE__* create() \
    { \
        __TYPE__ *pRet = new(std::nothrow) __TYPE__(); \
        if (pRet && pRet->init()) \
        { \
            pRet->autorelease(); \
            return pRet; \
        } \
        else \
        { \
            delete pRet; \
            pRet = NULL; \
            return NULL; \
        } \
    }
    

    the code

    CREATE_FUNC(MessageBoxes(std::string content));

    actually is

    new(std::nothrow) MessageBoxes(std::string content)();
    

    which has compile error in c++.

    but you can write the create funtion similar to CREATE_FUNC by yourself, like

    static MessageBoxes* create(std::string content) {
        MessageBoxes* ret = new(std::nothrow) MessageBoxes();
        if(ret && ret->init(content)) { //<----Or anything you wanna init with
            ret->autorelease();
            return ret;
        } else {
            delete ret;
            ret = nullptr;
            return nullptr;
        }
    }