cocos2d-x安卓系统中的Singleton

Singleton in cocos2d-x Android

本文关键字:Singleton 系统 cocos2d-x      更新时间:2023-10-16

我正在尝试编写一个用于维护游戏数据的singleton类,它被称为GameManager,就像《学习椰子2d》一书一样。

这是我的.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()"的引用,为什么第一个调用有效?

任何帮助都可以,谢谢!

您确定已将带有GameManager实现的cpp文件(您称之为"这是我的.cpp文件")包含在Android.mk文件中吗?