为什么静态成员变量会出现"undefined reference"链接错误?
Why do I get an "undefined reference" link error for a static member variable?
我有这个代码
文件: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++中的静态类变量"等主题。
相关文章:
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- Visual Studio Code "undefined reference to `WinMain@16'"
- 使用 MATLAB 编码器生成C++代码:编译错误"undefined reference to `rgb2gray_tbb_real64'"
- 为什么创建友元类的实例会导致"undefined reference to"错误?
- Tensorflow c++ api undefined reference to 'tflite::D efaultErrorReporter()'
- 为什么在使用 SDL2 时仍然收到'undefined reference'链接器错误?
- OpenCV undefined reference to 'cv::imread(cv::String const&, int)'
- Libcurl c++ "undefined reference to" (Windows/MinGW/g++)
- 尝试使用 extern "C" 调用 C 中的C++方法,得到"undefined reference to"对象的链接器错误
- build error : undefined reference to `yyFlexLexer::yyFlexLex
- 安卓 NDK 制造。数百"undefined reference error"
- 当我尝试进行TPC-E测试时,实用程序抱怨"undefined reference"
- 声明和定义函数静态会产生"undefined reference to function_name()"
- C++ : "undefined reference to"可能是因为CMake文件
- 包含<iostream>时"Undefined reference"错误
- CMake 'undefined reference' CERN-ROOT 的错误
- 生成错误:"cannot find target for file"和"undefined reference"
- AppData\Local\Temp\cc59LXDc.o:test1.cpp: undefined reference to 'constructNewObjectOfClass
- YAML-cpp 编译错误:"undefined reference to YAML::LoadFile"
- 添加 cpp11 插件时出现错误消息"Undefined reference to boost (...)"