访问静态变量C++时出现LNK2001错误

Mat*_*att 10 c++ static

我在尝试使用纹理时尝试在代码中使用静态变量,但是我不断收到此错误:

1>Platform.obj : error LNK2001: unresolved external symbol "private: static unsigned int Platform::tex_plat" (?tex_plat@Platform@@0IA)
Run Code Online (Sandbox Code Playgroud)

我已经在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;
};
Run Code Online (Sandbox Code Playgroud)

.cpp classes:这是变量初始化的地方

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我希望在此方法中使用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();
}
Run Code Online (Sandbox Code Playgroud)

有人可以解释这个错误.

4pi*_*ie0 18

静态成员必须在类体外定义,因此您必须添加定义并在那里提供初始化程序:

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
Run Code Online (Sandbox Code Playgroud)

也可以在类中初始化它,但是:

要使用该类内初始化语法,常量必须是由常量表达式初始化的整数或枚举类型的静态const.