【问题标题】:Static initialisation C++静态初始化 C++
【发布时间】:2012-08-02 21:40:47
【问题描述】:

我对 C++ 的有限理解意味着我不知道如何正确执行以下操作:

#include "Platform.h"
#include "Global.h"

SDL_Surface *ms_pSmall (Global::sharedGlobal()->loadImage(RESOURCE_SMALL_PLATFORM) );
SDL_Surface *ms_pMedium(Global::sharedGlobal()->loadImage(RESOURCE_MEDIUM_PLATFORM));
SDL_Surface *ms_pLarge (Global::sharedGlobal()->loadImage(RESOURCE_LARGE_PLATFORM) );

//Initialise platform variables
Platform::Platform()
{   
    int imgSize = rand() % 3;
    switch (imgSize)
    {
        case 2:
            m_pImage = ms_pSmall;
            break;
        case 1:
            m_pImage = ms_pMedium;
            break;
        case 0:
            m_pImage = ms_pLarge;
            break;
    }
}

其中 ms_pSmall 等是静态指针,Global 是具有以下函数声明的单例:

static Global* sharedGlobal();
SDL_Surface* loadImage(const std::string& filename) const;

代码似乎编译正确,但链接器抱怨:

Undefined symbols for architecture i386:"Platform::ms_pMedium", referenced from:
  Platform::Platform() in Platform.o    "Platform::ms_pLarge", referenced from:
  Platform::Platform() in Platform.o    "Platform::ms_pSmall", referenced from:
  Platform::Platform() in Platform.o 
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

[抱歉缩进不佳。]

这里的任何帮助都将不胜感激,我会很乐意展示更多代码,但我认为这就是人们需要了解我正在尝试做什么的全部内容。

提前致谢!

【问题讨论】:

    标签: c++ static initialization


    【解决方案1】:

    您需要对成员进行限定:

    SDL_Surface* Platform::ms_pSmall (Global::sharedGlobal()->loadImage(RESOURCE_SMALL_PLATFORM) );
    SDL_Surface* Platform::ms_pMedium(Global::sharedGlobal()->loadImage(RESOURCE_MEDIUM_PLATFORM));
    SDL_Surface* Platform::ms_pLarge (Global::sharedGlobal()->loadImage(RESOURCE_LARGE_PLATFORM) );
    

    否则,您只是声明了其他变量,而函数中的静态变量未定义。

    【讨论】:

    • 谢谢!我太愚蠢了 :( - 我只想勾选你的答案,但我必须再等 10 分钟。
    • 我现在确实有另一个问题,我希望得到帮助,我已经插入了几个断点,并且 loadImage() 似乎工作正常,但是在设置 m_pImage 的值时静态是 NULL 指针 - 知道为什么会这样吗?
    • @ArthurFox 如果不​​是这样,您将不得不发布一个新问题。
    • 如果你有一个Platform 的静态实例,那么你的代码已经被严重破坏了。请参阅 Luchian 的链接两个 cmets。
    猜你喜欢
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2023-03-31
    • 1970-01-01
    • 2012-01-16
    相关资源
    最近更新 更多