未定义对静态成员中的类静态成员的引用 [英] Undefined Reference to class static member in static member

查看:284
本文介绍了未定义对静态成员中的类静态成员的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中创建一个自引用类的链表,我想有一个名为startPointer的类型Item(Item是类名)的静态指针,所以当我调用我的静态成员函数free ,它可以通过使用Item :: startPointer释放内存,但我得到一个错误(显示在代码后)。 Pls帮助

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

在单个编译单元文件),否则刚才声明的成员。

Write such a line in a single compilation unit (cpp file), otherwise the member is just declared.

这篇关于未定义对静态成员中的类静态成员的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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