我试图重载<<运算符,以便我可以输出链表的内容.
所以,如果我有一个值为1,2,3的链表,我会调用:
cout << list << endl;
Run Code Online (Sandbox Code Playgroud)
其中list的类型为LinkedList.我应该得到类似的东西:
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;
}
Run Code Online (Sandbox Code Playgroud)
像这样的结构能否正常运作?:
LinkedList::report(ostream& outs) //thanks beta :)
{
Node *currentPtr = headPtr;
while(currentPtr != NULL)
{
outs << currentPtr->getData() << " "; //thanks Rob :)
currentPtr = currentPtr->getNextPtr();
}
return outs;
}
Run Code Online (Sandbox Code Playgroud)
我建议这个:
ostream& operator <<(ostream& outs, const LinkedList& source)
{
source.report(outs);
return outs;
}
Run Code Online (Sandbox Code Playgroud)
此方法看不到节点类.您将实现保留在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
}
Run Code Online (Sandbox Code Playgroud)