2011-09-05 129 views
2

我試圖超載< <運算符,所以我可以輸出鏈表的內容。Overloading << C++

所以,如果我與值1,2,3一鏈表和我稱:

cout << list << endl; 

其中列表的類型是鏈表的。我應該得到這樣的東西:

1 2 3或1 | 2 | 3在終端。

我應該使用循環遍歷列表並將每個節點的數據添加到輸出?想實現,這並不需要看到節點類的方法...

ostream& operator <<(ostream& outs, const LinkedList& source) 
{ 

    //use a loop to cycle through, adding each data to outs, seperated by a space or a | 

    return outs; 
} 

謹以此制定出一個結構好嗎?:

LinkedList::report(ostream& outs) //thanks beta :) 
{ 
    Node *currentPtr = headPtr; 

    while(currentPtr != NULL) 
    { 
     outs << currentPtr->getData() << " "; //thanks Rob :) 

     currentPtr = currentPtr->getNextPtr(); 
    } 

    return outs; 
} 
+1

你可能想看看[this](http://stackoverflow.com/questions/4850473/pretty-print-c-stl-containers)(; – Mankarse

+1

它是功課嗎? – amit

+0

你的'LinkedList'類是模板嗎? –

回答

7

我建議這樣的:

ostream& operator <<(ostream& outs, const LinkedList& source) 
{ 
    source.report(outs); 
    return outs; 
} 

此方法看不到節點類。你在LinkedList::report(ostream& outs)中保留你的實現 - 你使用循環。

編輯:
一對夫婦更正到您的report方法:

// It must have a return type (e.g. void), and it must be const because your 
// operator takes a const argument, which must call this method 
void LinkedList::report(ostream& outs) const 
{ 
    const Node *currentPtr = headPtr; // might as well make this const too 

    while(currentPtr != NULL) 
    { 
     outs << currentPtr->getData() << " "; // you can use "|" if you want 
     currentPtr = currentPtr->getNextPtr(); 
    } 

    // no need to return anything 
} 
+0

試圖在這裏添加一個潛在的循環,而不是你可以編輯其他人的帖子:P – Cheeseman

3

是的,你應該實現一個循環通過您LinkedList類進行迭代。

既然你不顯示怎麼LinkedList的作品,我不能告訴你,在循環正是去,但一般可能是這樣的:

ostream& operator<<(ostream& outs, const LinkedList& source) { 
    while(there_remains_data_to_print(source)) { 
     outs << get_the_next_datum(source) << " "; 
    } 
    return source; 
} 

例如,如果您有LinkedList STL風格的迭代器:

ostream& operator<<(ostream& outs, const LinkedList& source) { 
    LinkedList::iterator it = source.begin(); 
    while(it != source.end()) { 
     outs << *it << " "; 
     ++it; 
    } 
    return source; 
} 

或者,對於傳統的C風格的鏈接列表:

ostream& operator<<(ostream& outs, LinkedList source) { 
    while(source) { 
     outs << source->datum << " "; 
     source = source->next; 
    } 
    return source; 
} 
+0

唉,你會產生一個無關的最後的分隔符,OP可能不喜歡(因爲他希望使用'|'作爲分隔符)。 –

+0

@Kerrek - 是的,我想過添加邏輯來避免這種情況,但留下來「作爲練習給讀者」。 –