2016-11-12 74 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流,因为至少头指针应该有印刷...