LNK2001错误访问静态变量的C++
问题描述:
我试图尝试使用纹理时要使用一个静态变量在我的代码,但我不断收到此错误时:LNK2001错误访问静态变量的C++
1>Platform.obj : error LNK2001: unresolved external symbol "private: static unsigned int Platform::tex_plat" ([email protected]@@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();
}
有人可以解释这个错误。
答
静态成员必须类体之外定义,所以你要添加的定义,并提供初始化有:
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
也可以将其初始化类内部,而是:
To use that in-class initialization syntax, the constant must be a static const of integral or enumeration type initialized by a constant expression.
答
补充一点:
GLuint Platform::tex_plat;
类声明之后。
可能的重复[什么是未定义的引用/无法解析的外部符号错误,以及如何解决它?](http://*.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol - 错误和知识-DO-修复) – chris 2013-04-06 00:43:35