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

时间:2013-04-06 00:41:04

标签: c++ static

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

1>Platform.obj : error LNK2001: unresolved external symbol "private: static unsigned int Platform::tex_plat" (?tex_plat@Platform@@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();
}

可以解释一下这个错误。

2 个答案:

答案 0 :(得分:15)

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

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

也可以在课堂内初始化它,但是:

  

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

答案 1 :(得分:0)

添加:

GLuint Platform::tex_plat;
在你的课堂宣言之后

相关问题