【问题标题】:Singleton in cocos2d-x Androidcocos2d-x Android 中的单例
【发布时间】:2012-02-24 16:33:05
【问题描述】:

我正在尝试写一个用于维护游戏数据的单例类,它叫GameManager,就像出品的《学习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()' 的引用,为什么第一次调用有效?

任何帮助都可以,谢谢!

【问题讨论】:

    标签: android c++ android-ndk singleton cocos2d-x


    【解决方案1】:

    您确定已将您的 cpp 文件与 GameManager 实现(您称之为“这是我的 .cpp 文件”)一起包含到您的 Android.mk 文件中吗?

    【讨论】:

    • 谢谢亚历克斯,我以为是因为单例,但不是。我将 cpp 文件添加到我的 Android.mk 文件中,它可以工作。
    猜你喜欢
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    相关资源
    最近更新 更多