【问题标题】:What is wrong with my overloaded operator<< function?我的重载 operator<< 函数有什么问题?
【发布时间】:2016-11-12 05:20:42
【问题描述】:
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;
}
程序编译成功,但不打印任何内容。可能是什么问题?
【问题讨论】:
标签:
linked-list
operator-overloading
【解决方案1】:
您需要使用i 而不是rhs.head
while (i != 0)
{
out << " " << i;
i = i->next;
}
rhs.head != 0 不能被循环中的内容改变,所以如果为假,则循环永远不会运行,如果为真,它将永远循环。
i = rhs.head->next; 也将始终将i 设置为第二个节点(头部之后的那个),而不是i 之后的那个。
【解决方案2】:
我假设输入列表为空,因此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流是什么,因为至少应该在那里打印头指针...