简体   繁体   中英

LNK2001 error when accessing static variables C++

I'm trying to use a static variable in my code when trying to use textures, however I keep getting this error:

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

I have initialised the variable properly in the cpp file, however I believe this error occurs when trying to access it in another method.

.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 classes: This is where the variable is initialised

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

I then wish to use the tex_plat value in this method:

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

could some one explain this error.

Static member must be defined outside class body, so you have to add the definition and provide initializer there:

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

It is also possible to initialize it inside your class but:

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

add this:

GLuint Platform::tex_plat;

after your class declaration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM