2011-09-05 140 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 - 是的,我想过添加逻辑来避免这种情况,但留下来“作为练习给读者”。 –