为什么我会收到“未定义的参考"?静态成员变量的链接错误? [英] Why do I get an "undefined reference" link error for a static member variable?

查看:54
本文介绍了为什么我会收到“未定义的参考"?静态成员变量的链接错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码

文件: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;
};

但是当我尝试构建它时,链接器显示此错误:

But when I try to build it, the linker shows this error:

对Living :: spriteImg的未定义引用

Undefined reference to Living::spriteImg

我不知道该如何解决-有什么问题?

I have no idea how to fix this -- what's the problem?

推荐答案

您声明了spriteImg,但从未对其进行定义.在living.cpp中,尝试添加以下内容:

You declared spriteImg, but never defined it. In living.cpp, try adding the following:

Sprite* Living::spriteImg = NULL;

自声明以来,编译器允许您对其进行引用,并期望链接程序将解析该引用.由于永远都没有定义,因此链接器无法这样做,并且会抱怨.

Since you declared it, the compiler allows you to reference it, and expects that the linker will resolve the reference. Since there is never a definition, the linker can't do so, and it complains.

编辑:如果您想了解更多有关此处发生的情况的信息,请研究诸如C ++中的编译单元",编译",链接"和静态类变量"之类的主题."

if you would like to learn more about what's going on here, research topics such as "compilation units," "compiling," "linking," and "static class variables in C++."

这篇关于为什么我会收到“未定义的参考"?静态成员变量的链接错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆