【问题标题】:Operator << in a class for queue队列类中的运算符 <<
【发布时间】:2014-03-08 01:56:21
【问题描述】:

我在定义我的运算符时遇到了一个小问题:

运算符的代码是:

ostream& operator<< (ostream& outs, const IntQueue& queue)
{
    NodePtr temp = queue.head;
    while(temp->link != NULL)
    {
        outs << temp->data;
        outs << " ";
    }
    outs << endl;
    return outs;
}

我希望操作员显示队列中所有节点以及最后一个节点(指向 NULL)的 temp->data。我不知道如何修改 while 循环,所以它也会写出最后一项(指向 NULL)。

希望我说清楚了。

干杯。

【问题讨论】:

  • 请发布IntQueue的定义。
  • 看起来你没有在你的循环中“推进”temp。这很糟糕(无限循环)。您是否只想为NULL 打印“NULL”?否则你希望它如何打印?

标签: c++ linked-list operator-overloading


【解决方案1】:

需要纠正的几点:

  • 正如 cmets 中所指出的,在 while 循环内确保使用类似

    的东西推进指针

    temp = temp->链接;

  • 将循环编辑为 do-while 循环。这样你就可以确定它甚至会打印出最后一个节点。

  • 使用 do-while 循环后,您需要对 temp 添加额外的 NULL 检查以处理“空”列表情况。

最后,作为补充一点,您可以考虑为 Node 对象本身重载 '

ostream& operator<< (ostream& outs, const IntQueue& queue)
{
    Node* temp = queue.head;
    if(NULL != temp) {
        do
        {
            outs << temp;
            temp = temp->link;
        }
        while(temp->link != NULL);
    }
    return outs;
}

【讨论】:

    【解决方案2】:

    尝试以下方法:

    ostream& operator<< (ostream& outs, const IntQueue& queue)
    {
        NodePtr temp = queue.head;
        while(temp != NULL)
        {
            outs << temp->data;
            outs << " ";
            temp = temp->link;
        }
        outs << endl;
        return outs;
    }
    

    【讨论】:

      【解决方案3】:
      ostream& operator <<( ostream& outs, const IntQueue& queue )
      {
          for ( NodePtr temp = queue.head; temp; temp = temp->link )
          {
              outs << temp->data;
              outs << " ";
          }
      
          outs << endl;
      
          return outs;
      }
      

      【讨论】:

        【解决方案4】:

        您可以尝试使用 do-while 循环,这样它在上次完成操作之前不会检查 NULL。

        我想这将允许您打印出 NULL 作为最终值。

        【讨论】:

        • temp-&gt;datatempNULL 会导致什么?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-21
        • 2020-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多