访问静态变量 C++ 时出现 LNK2001 错误 [英] LNK2001 error when accessing static variables C++

查看:46
本文介绍了访问静态变量 C++ 时出现 LNK2001 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

我已经在 cpp 文件中正确地初始化了变量,但是我相信在尝试以另一种方法访问它时会发生此错误.

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 类:这是变量初始化的地方

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

然后我希望在这个方法中使用 tex_plat 值:

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.

这篇关于访问静态变量 C++ 时出现 LNK2001 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆