链表输出崩溃

Linked List output crash

本文关键字:崩溃 输出 链表      更新时间:2023-10-16

程序在输出链表内容时挂起。我不能更改头文件,只能更改cpp文件。

playlist.h:

class PlayList {
    private:
    struct SongNode {
        Song data;
        SongNode* next;
        SongNode (const Song& s, SongNode* nxt = 0)
          : data(s), next(nxt)
        {}
    };
    friend std::ostream& operator<< (std::ostream& out, const PlayList& s);
    SongNode* first; // head of a list of songs, ordered by title, then artist
    //Snip...
    inline
    std::ostream& operator<< (std::ostream& out, const PlayList& pl)
    {
        for (PlayList::SongNode* current = pl.first; current != 0; current = current->next)
            out << current->data << std::endl;
        return out;
    }

playlist.cpp

using namespace std;

PlayList::PlayList()
    : totalTime(0,0,0)
{
}

void PlayList::operator+= (const Song& song)
{
    SongNode* newNode = new SongNode(song, first);
    first = newNode;
}

当输出列表时,所有应该打印的数据都打印出来了,但是随后程序挂起了

class PlayList的构造函数中,需要初始化first:

public:
    PlayList() : first(NULL) {}

否则,在你的operator<<中,你到达列表的末尾,而不是遇到NULL,你只是得到一个垃圾指针。

您忘记在构造函数中初始化first