其他分享
首页 > 其他分享> > 在cocos2d-x Android中的单例

在cocos2d-x Android中的单例

作者:互联网

我正在尝试编写一个用于维护游戏数据的单例类,即GameManager,就像这本书《 Learning cocos2d》一样.

这是我的.h文件:

#ifndef GameManager_h
#define GameManager_h

#include "cocos2d.h"

class GameManager
{
private:
    //Constructor
    GameManager();

    //Instance of the singleton
    static GameManager* m_mySingleton;

public:    
    //Get instance of singleton
    static GameManager* sharedGameManager();    

    //A function that returns zero "0" 
    int ReturnZero(){return 0;}
    // another test function
    void runScene() { CCLOG("test");};

};

这是我的.cpp文件:

#include "SimpleAudioEngine.h"
#include "GameManager.h" 
using namespace cocos2d;
using namespace CocosDenshion;

//All static variables need to be defined in the .cpp file
//I've added this following line to fix the problem
GameManager* GameManager::m_mySingleton = NULL;

GameManager::GameManager()
{    

}

GameManager* GameManager::sharedGameManager()
{
    //If the singleton has no instance yet, create one
    if(NULL == m_mySingleton)
    {
        //Create an instance to the singleton
        m_mySingleton = new GameManager();
    }

    //Return the singleton object
    return m_mySingleton;
}

这是HelloWorld.cpp中的调用:

void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event) {
    CCLOG("return zero:%d",GameManager::sharedGameManager()->ReturnZero());  // Line 231
    GameManager::sharedGameManager()->runScene();  // Line 232
}

这是一个奇怪的问题,它与xcode配合良好,可以在iPhone上构建.但是当我尝试使用ndk进行构建时:

./obj/local/armeabi/objs-debug/game_logic/HelloWorldScene.o: In function `HelloWorld::ccTouchesEnded(cocos2d::CCSet*, cocos2d::CCEvent*)':
/Users/abc/Documents/def/def/android/jni/../../Classes/HelloWorldScene.cpp:232: undefined reference to `GameManager::sharedGameManager()'
collect2: ld returned 1 exit status
make: *** [obj/local/armeabi/libgame_logic.so] Error 1

如果未定义引用`GameManager :: sharedGameManager()’,为什么第一个调用仍在起作用?

任何帮助都可以,谢谢!

解决方法:

您确定您已经将cpp文件包含在GameManager实现中(您将其称为“这是我的.cpp文件”)包含在Android.mk文件中吗?

标签:cocos2d-x,android-ndk,singleton,c-4,android
来源: https://codeday.me/bug/20191201/2082659.html