C++重载operator/输出Circle二叉树SVG内容时输出缺失问题排查
问题根因
你重载的operator/函数声明要求返回ostream&类型,但整个函数实现中没有写return语句返回输入的流对象,这属于未定义行为。C++中如果一个非void返回值的函数执行结束没有显式返回对应类型的值,后续对返回值的操作结果完全不可预期:第一次调用osInput / *firstCircle之后返回的流是非法的,第二次调用osInput / *secondCircle自然无法正常执行,调换两个子节点的调用顺序也只会有第一个能正常执行,和你遇到的现象完全吻合。
修复方案
只需要在operator/函数的末尾加上返回流对象的语句即可,修改后的代码如下:
ostream& operator/(ostream& osInput, Circle& circle) { if (circle.isLeaf()) { osInput << " <circle cx=\"" << circle.centerX << "\" cy=\"" << circle.centerY <<"\" radius=\"" << circle.radius << "\" style=\"fill:blue;stroke:black;stroke-width:.05;fill-opacity:.1;stroke-opacity:.9\"/>\n"; } else { osInput << " <circle cx=\"" << circle.centerX << "\" cy=\"" << circle.centerY <<"\" radius=\"" << circle.radius << "\" style=\"fill:yellow;stroke:black;stroke-width:.05;fill-opacity:.0;stroke-opacity:.5\"/>\n"; Circle* firstCircle = circle.getFirstSubcircle(); Circle* secondCircle = circle.getSecondSubcircle(); osInput / *firstCircle; osInput / *secondCircle; } // 新增返回流的语句 return osInput; }
内容的提问来源于stack exchange,提问作者Wesley Brandt
相关产品推荐
相关产品推荐

