Undefined Reference to class static member in static member(静态成员中对类静态成员的未定义引用)
问题描述
我在 C++ 中创建了一个带有自引用类的链表,我想要一个名为startPointer"的类型为 Item(Item 是类名)的静态指针,以便当我调用我的静态成员函数free"时,它可以通过使用 Item::startPointer 释放内存,但我收到一个错误(在代码后显示).请帮助,
I am creating a linked list with self referential class in C++ and I want to have a static pointer of the type Item (Item is the class name) named "startPointer" so that when i call my static member function "free" , it can free up the memory by using Item::startPointer but i am getting an error(shown after code). Pls Help,
class Item
{
public:
std::string name;
int row,column;
int fileType;
Item *ptr;
static Item *startPointer;
void setNextPointer(Item* ptr)
{
ptr=ptr;
}
Item *getNextPointer()
{
return ptr;
}
static void free()
{
Item *p,*temp;
p=startPointer;
while(p!=NULL)
{
temp=p;
p=p->getNextPointer();
delete temp;
}
}
};
<小时>
cube.o:cube.cpp:(.text$_ZN4Item4freeEv[Item::free()]+0x8): undefined reference to `Item::startPointer'
collect2: ld returned 1 exit status
mingw32-make.exe: *** [cube.exe] Error 1
Execution terminated
推荐答案
你必须像这样定义你的静态成员:
You have to define your static member like this:
Item* Item::startPointer = nullptr; // or = NULL; if your cpp version is below c++11
在单个编译单元(cpp文件)中写这样一行,否则只是声明成员.
Write such a line in a single compilation unit (cpp file), otherwise the member is just declared.
这篇关于静态成员中对类静态成员的未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:静态成员中对类静态成员的未定义引用
- C++ 协变模板 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 静态初始化顺序失败 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01