C++指针链表

标签 c++

所以我是 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.: 当您不再需要该实例时,不要忘记删除它。

关于C++指针链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26208645/

相关文章:

c++ - 如何通过 unsigned long 将 std::shared_ptr 传递给回调?

c++ - 是否可以通过共享内存从不同进程更新 Eigen3 或其他矩阵库 2D 矩阵?

c++通过串行通信发送ascii 254

c++ - 用 C++ 编写和读取 Unicode 文件?

c++ - 编译器如何从Deleted-default-ctor lambda生成闭包?

c++ - 如何通过控制台/C++ 与程序通信

c++ - 如何将 boost asio tcp 套接字传递给线程以向客户端或服务器发送心跳

c++ - G++ : Moving to another translation unit breaks "const optimization"?

c++ - 为什么不能在 C++ 类中重新定义类型名称?

c++ - 查找已安装的正确 Boost 版本以及如何删除旧版本