2012-08-02 101 views
3

我有限的C++的理解是指我不知道如何正确地做到以下几点:静态初始化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等都是静态的指针和全球是用下面的函数声明一个单:

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) 

[对不起,可怜的缩进。]

任何帮助在这里将不胜感激,我会高兴地显示更多的代码,但我认为这是所有人需要了解我想要做的。

在此先感谢!

回答

8

您需要限定成员:

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)); 

否则你只是在声明其他变量,并从功能静没有定义。

+0

谢谢!这样的愚蠢在我的部分:( - 我只是想勾选你的答案,但我必须等待10多分钟 – Arthur 2012-08-02 21:44:06

+0

我现在有另一个问题,我将不胜感激帮助,我已经推了几个断点和loadImage()似乎工作正常,但当涉及到设置m_pImage的值所有的静态都是NULL指针 - 任何线索为什么可能是? – Arthur 2012-08-02 21:59:40

+1

@ArthurFox也许http://stackoverflow.com/questions/335369/finding-c- static-initialization-order-problems – 2012-08-02 22:07:05