【问题标题】:Linked List output crash链表输出崩溃
【发布时间】:2011-12-02 00:31:41
【问题描述】:

我的程序在输出链接列表的内容时挂起。我无法更改标题,只能更改 cpp 文件。

播放列表.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;
    }

播放列表.cpp

using namespace std;



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


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

当输出列表所有应该打印的数据时,确实打印,但随后程序挂起。

【问题讨论】:

    标签: c++ linked-list


    【解决方案1】:

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

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

    否则,在您的operator&lt;&lt; 中,您会到达列表末尾,而不是遇到NULL,您只会得到一个垃圾指针。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-20
        • 2019-02-22
        • 1970-01-01
        相关资源
        最近更新 更多