2013-04-06 43 views
4

我試圖嘗試使用紋理時要使用一個靜態變量在我的代碼,但我不斷收到此錯誤時:LNK2001錯誤訪問靜態變量的C++

1>Platform.obj : error LNK2001: unresolved external symbol "private: static unsigned int Platform::tex_plat" ([email protected]@@0IA) 

我在正確初始化變量cpp文件,但是我相信當嘗試以另一種方法訪問它時會發生此錯誤。

.H

class Platform : 
public Object 
{ 
    public: 
     Platform(void); 
     ~Platform(void); 
     Platform(GLfloat xCoordIn, GLfloat yCoordIn, GLfloat widthIn); 
     void draw(); 
     static int loadTexture(); 

    private: 
     static GLuint tex_plat; 
}; 

的.cpp類: 這是其中變量被初始化

int Platform::loadTexture(){ 
GLuint tex_plat = SOIL_load_OGL_texture(
      "platform.png", 
      SOIL_LOAD_AUTO, 
      SOIL_CREATE_NEW_ID, 
      SOIL_FLAG_INVERT_Y 
      ); 

    if(tex_plat > 0) 
    { 
     glEnable(GL_TEXTURE_2D); 
     return tex_plat; 
    } 
    else{ 
     return 0; 
    } 
} 

然後我希望在該方法中使用tex_plat值:

void Platform::draw(){ 
    glBindTexture(GL_TEXTURE_2D, tex_plat); 
    glColor3f(1.0,1.0,1.0); 
    glBegin(GL_POLYGON); 
    glVertex2f(xCoord,yCoord+1);//top left 
    glVertex2f(xCoord+width,yCoord+1);//top right 
    glVertex2f(xCoord+width,yCoord);//bottom right 
    glVertex2f(xCoord,yCoord);//bottom left 
    glEnd(); 
} 

有人可以解釋這個錯誤。

+1

可能的重複[什麼是未定義的引用/無法解析的外部符號錯誤,以及如何解決它?](http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol - 錯誤和知識-DO-修復) – chris 2013-04-06 00:43:35

回答

10

靜態成員必須類體之外定義,所以你要添加的定義,並提供初始化有:

class Platform : 
public Object 
{ 
    public: 
     Platform(void); 
     ~Platform(void); 
     Platform(GLfloat xCoordIn, GLfloat yCoordIn, GLfloat widthIn); 
     void draw(); 
     static int loadTexture(); 

    private: 
     static GLuint tex_plat; 
}; 

// in your source file 
GLuint Platform::tex_plat=0; //initialization 

也可以將其初始化類內部,而是:

To use that in-class initialization syntax, the constant must be a static const of integral or enumeration type initialized by a constant expression.

0

補充一點:

GLuint Platform::tex_plat; 

類聲明之後。