gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 15:49:20 29 4
gpt4 key购买 nike

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

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

谁能解释这个错误。

最佳答案

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

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.

关于c++ - 访问静态变量 C++ 时出现 LNK2001 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15845745/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com