为什么静态成员变量会出现"undefined reference"链接错误?

Why do I get an "undefined reference" link error for a static member variable?

本文关键字:undefined reference 错误 链接 静态成员 变量 为什么      更新时间:2023-10-16

我有这个代码

文件:Gnome.cpp

#include "Living.h"
class Gnome : public Living {
public:
    Gnome();
    void drawObjects();
};

Gnome::Gnome()
{
  // **** The line below is where the error occurs **** 
  spriteImg = new Sprite("graphics/gnome.bmp");  
  loaded = true;
}

文件:Living.h

#include <iostream>  
#include "Sprite.h"

using namespace std;
class Sprite;
class Living {
protected:
    int x,y;
    static Sprite *spriteImg; //= NULL;
    bool loaded;
    void reset();
public:
    Living();
    ~Living();
    int getX();
    void setX(int _x);
    int getY();
    void setY(int _y);
    void virtual drawObjects() =0;
};

但当我尝试构建它时,链接器显示了以下错误:

未定义的引用Living::spriteImg

我不知道怎么解决这个问题——出了什么问题?

您声明了spriteImg,但从未定义过它。在living.cpp中,尝试添加以下内容:

Sprite* Living::spriteImg = NULL;

由于您声明了它,编译器允许您引用它,并期望链接器解析该引用。由于从来没有定义,链接器不能这样做,它会抱怨。

编辑:如果您想了解更多关于这里发生的事情,请研究"编译单元"、"编译"、"链接"answers"C++中的静态类变量"等主题。