【问题标题】:Why is my overloaded << operator not outputting the last line?为什么我的重载 << 运算符没有输出最后一行?
【发布时间】:2016-06-19 10:24:07
【问题描述】:
ostream& operator<< (ostream& os,SparseMatrix& m)
{
RowNode* rowPoint = m.rowFront;
Node* point = rowPoint->firstInRow;


while(rowPoint != NULL)
    {
    while (point != NULL)
        {
        os << point->row;
        os << ' ';
        os << point->column;
        os << ' ';
        os << point->data;
        os << endl;
        point = point->right; 
        }
    rowPoint = rowPoint->nextRow;
    point = rowPoint->firstInRow;
    }

os << "0 0 0" << endl;

return os;
}

当我尝试在我的程序中运行它时,列表完全正确,但最后的“0 0 0”行从未出现。我尝试以不同的方式对其进行格式化,将其放在较大的 while 循环末尾的 if 语句中,我什至尝试输出一堆不仅仅是“0 0 0”以查看它是否可以打印任何东西,但没有骰子。

如果有人需要查看更多代码,我很乐意提供!

【问题讨论】:

  • 根据您的代码,如果rowPoint 为NULL 或point 为NULL,则不会发生打印。我建议使用调试器并观察这两个变量。

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


【解决方案1】:

在您的循环中,当您到达最后一个元素时,rowPoint 将设置为 NULL,rowPoint = rowPoint-&gt;nextRow;

不幸的是,在下一条语句中,您在检查它是否为 NULL 之前取消引用该空指针:

point = rowPoint->firstInRow;

这会导致 UB。

为了解决这个问题,稍微改变你的代码:

ostream& operator<< (ostream& os,SparseMatrix& m)
{
RowNode* rowPoint = m.rowFront;

while(rowPoint != NULL)
    {
    Node* point = rowPoint->firstInRow;  // here you're sure not to dereference NULL ptr
    while (point != NULL)
        {
        ...
        point = point->right; 
        }
    rowPoint = rowPoint->nextRow;
    }
...
}

【讨论】:

  • 我只是在输入我自己问题的答案,因为我在发布此问题后马上就明白了......
【解决方案2】:
rowPoint = rowPoint->nextRow;
point = rowPoint->firstInRow;

rowPoint 最终会返回一个nullptr,而point 将使用该无效指针来访问firstInRow,这将使您的应用程序崩溃并且代码os &lt;&lt; "0 0 0" &lt;&lt; endl; 将永远不会被执行。或者nextRow 永远不会返回 null(因此你的循环永远不会结束)。

解决方案:

while (rowPoint != NULL)
{
    point  = rowPoint->firstInRow;

    while (point != NULL)
    {
        os << point->row;
        os << ' ';
        os << point->column;
        os << ' ';
        os << point->data;
        os << endl;
        point = point->right;
    }

    rowPoint = rowPoint->nextRow;
}

【讨论】:

    猜你喜欢
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    • 2011-01-21
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多