[英]LNK2001 error when accessing static variables C++
我在尝试使用纹理时尝试在代码中使用静态变量,但是我不断收到此错误:
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 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;
}
}
然后我希望在此方法中使用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();
}
有人可以解释这个错误。
静态成员必须在类体外定义,因此您必须添加定义并在那里提供初始化程序:
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
也可以在类中初始化它,但是:
要使用该类内初始化语法,常量必须是由常量表达式初始化的整数或枚举类型的静态const。
添加这个:
GLuint Platform::tex_plat;
在你的课堂宣言之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.