2016-11-12 76 views
0
ostream & operator<<(ostream &out, const IntList &rhs) 
{ 
    IntNode *i = rhs.head; 
    out << rhs.head; 
    while (rhs.head != 0) 
    { 
     out << " " << i; 
     i = rhs.head->next; 
    } 

    return out; 
} 

該程序編譯成功,但不打印任何東西。可能是什麼問題呢?我的重載運算符<<函數有什麼問題?

回答

0

您需要使用i代替rhs.head

while (i != 0) 
{ 
    out << " " << i; 
    i = i->next; 
} 

rhs.head != 0不能被循環內容改變,所以如果它是假的,循環將永遠不會運行,如果它是真的,它將永遠循環。

i = rhs.head->next;將始終將i設置爲第二個節點(頭後),而不是i後。

0

我假設輸入列表是空的,因此rhs.head != 0條件失敗?否則它實際上會導致無限循環,因爲rhs.head被測試而不是i。我想這應該是:

IntNode *i = rhs.head; 
out << rhs.head; 
while (i != 0) // note the i here 
{ 
    out << " " << i; 
    i = i->next; // again i here 
} 

第二個問題是什麼是out流,因爲至少頭指針應該有印刷...