繁体   English   中英

C ++指针链接列表

[英]C++ pointer linked list

所以我对c ++还是陌生的,如果还不清楚的话。

我有一堂课:

class Item
{
    int noItem;
    int qItem;
public:
    Item(int noItem, int qItem)
    {
            this->noItem = noItem;
            this->qItem = qItem;
    }

    int getNoItem()
    {
            return noItem;
    }

    int getQntItem()
    {
            return qItem;
    }
};

然后是下面的类:

class Element
{
public:
    Element()
    {
            data = NULL;
    }

    //to set and access data hold in node
    void setElement(Item *data)
    {
            this->data = data;
    }
    Item* getElement(void)
    {
            return(data);
    }

private:
    Item *data;
};

这个也:

class ListeChainee
{
public:

    ListeChainee()
    {
        courant = NULL;
    }
    void ajoutListe(Item *data)
    {
        Element *newData;

        //set data
        newData->setElement(data);

        //check if list is empty
        if( courant == NULL)
        {           
            //set current pointer
            courant = newData;
        }


    }

    //get data from element pointed at by current pointer
    Item* elementCourant(void)
    {
            if(courant != NULL)
            {
                return courant->getElement();
            }
            else
            {
                return NULL;
            }
    }

private:
    //data members
    Element *courant;           //pointer to current element in list

};

代码缺少其他内容,但是我的问题是:

int main(int argc, char* argv[])
{
    ListeChainee listeCH;
    Item i1(123,456);

    listeCH.ajoutListe(&i1);

    cout << listeCH.elementCourant()->getNoItem();

    system("pause");

    return 0;
}

我希望输出123,但我看到其他数字。 不知道为什么。 谢谢。

您的Element *newData没有Element类的实例,因此当您尝试访问newData指向的实例时,它将崩溃。

尝试更改Element *newData; Element *newData = new Element;

  • ps .:当您不再需要该实例时,请不要忘记delete它。

该方法正在写入未初始化的内存:

void ajoutListe(Item *data)
{
    Element *new;

    //set data
    new->setElement(data); // Right here, "new" is an uninitialized pointer

    //check if list is empty
    if( courant == NULL)
    {           
        //set current pointer
        courant = new;
    }
}

我对此编译感到惊讶(是吗?)。 此代码也应该崩溃。

您得到的奇数肯定是内存中的随机部分。 您可能想更多地考虑内存管理-这里有很多问题。 调用ajoutListe时,为什么courant成员只有在它为NULL时才被设置? 我们只是泄漏新元素吗? 我们实际上如何遍历此列表?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM