我正在尝试在Cocos2d-X中创建一个回调函数。我有一个单例课程(AdsMgr)。在AdsMgr中,我想存储函数指针。我应该如何用传入参数替换callBackPauseResume?

AdsMgr.h

class AdsMgr
{
private:
    static bool isAdsEnabled();

public:
    static void(*callBackPauseResume)(int index);
    static void initAds(void(*incallback)(int index));
}


AdsMgr.mm

void AdsMgr::initAds(void(*incallback)(int index))
{
    callBackPauseResume = incallback;

//    incallback(1);
}


MainScene.cpp

if(btn4 && btn4->getBoundingBox().containsPoint(location))
{
     CCLOG("SHOW INTERSTITIAL");
     AdsMgr::initAds(MainScene::pauseResumeDuringAds);
}

void MainScene::pauseResumeDuringAds(int inFlag)
{
    switch (inFlag) {
        case 0:
        // Pause game
            break;
        case 1:
            // Resume Game
            break;
        default:
            break;
    }
}


我无法编译,并遇到以下错误:

Undefined symbols for architecture arm64:
  "AdsMgr::callBackPauseResume", referenced from:
      AdsMgr::initAds(void (*)(int)) in AdsMgr.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

最佳答案

根据编译错误判断,您尚未定义callBackPauseResume变量。这就是错误的意思。

除了在类内部进行声明外,还需要在类之外的AdsMgr.mm中为其添加一个定义:

void (*AdsMgr::callBackPauseResume)(int) = nullptr;

10-08 14:26