2011-12-02 78 views
4

我的程序在輸出鏈接列表的內容時掛起。我不能更改標題,只有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; 
} 

當輸出列表中的所有是應該打印的數據,可以打印,但隨後的程序掛起。

回答

6

class PlayList構造函數中,你需要初始化first

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

否則,你operator<<,你到達列表的末尾,而不是遇到NULL,你只是得到一個垃圾指針。

4

你忘了在構造函數初始化first