对静态成员函数中静态成员变量的未定义引用

undefined reference to static member variable in a static member function

本文关键字:静态成员 未定义 引用 函数 变量      更新时间:2023-10-16

这是我的头文件:

class MapObject: public ScreenObject {
    static float xoffset, yoffset;
public:
    static float Getxoffset() {
        return xoffset;
    }
};
#endif // MAPOBJECT_H

然而,在线上返回xoffset;我得到以下错误:对"MapObject::xoffset"的未定义引用为什么?

将其放入源文件(看起来是MapObject.cpp

#include "MapObject.h"
float MapObject::xoffset = 0;
float MapObject::yoffset = 0;

//... the rest of your MapObject code here...

在C++中,非常量static成员必须在类定义中声明,并且定义的具有全局作用域,才能正确地为链接器提供可引用的内容。

你的MapObject.cpp:中必须有这样的东西

float MapObject::xoffset = 0.0f;
float MapObject::yoffset = 0.0f;

通过这种方式,您可以定义初始化它们。