【问题标题】:Why do I get a SIGSEGV when I use my overloaded insertopm (<<) operator?当我使用重载的 insertopm (<<) 运算符时,为什么会得到 SIGSEGV?
【发布时间】:2016-10-05 05:43:32
【问题描述】:

我正在学习 C++ 课程,对于我最近的作业,我必须创建一个 Box 课程。总的来说,这项任务实际上是在公园里散步,但我在使用我应该创建的重载插入运算符时遇到了一些问题。插入运算符在box.h 中声明,并在box.cpp 中定义,这是标准的。在Box 类中,我有一个print(std::ostream &amp;) const 函数。重载的插入操作符所做的只是调用提供给操作符的std::ostream &amp; 上的print 函数。相关代码:

void Box::print(std::ostream &outStream) const { // The java in me loves abstraction
    if ((_boxType == BoxType::FILLED) || (_boxType == BoxType::HOLLOW))
        _printFilledOrHollow(outStream);
    else if (_boxType == BoxType::CHECKERED)
        _printCheckered(outStream);
}

void Box::_printFilledOrHollow(std::ostream &outStream) const {
    if (_width > 1) {
        outStream << string(_width, 'x') << endl;
        for (int i = 0; i < (_height - 2); i++) { //works for everything but 1
            if (_boxType == Box::FILLED)
                outStream << string(_width, 'x') << endl;
            else
                outStream << "x" << string((_width - 2), ' ') << "x" << endl;
        }
        outStream << string(_width, 'x') << endl;
    } else
        outStream << "x" << endl; //which is what this is for
}

void Box::_printCheckered(std::ostream &outStream) const {
    if (_boxType == Box::CHECKERED) {
        for (int row = 0; row < _height; row++) {
            for (int col = 0; col < _width; col++) {
                if ((row % 2) == 0) { // if even column
                    if (col % 2 == 0)
                        outStream << "x";
                    else
                        outStream << " ";
                } else {
                    if ((col % 2) != 0)
                        outStream << "x";
                    else
                        outStream << " ";
                }
            }

            cout << endl;
        }
    }
}

std::ostream &operator<<(std::ostream &outStream, const Box &rhs) {
    rhs.print(outStream);
}

现在,这是真正奇怪的部分。如果我在cout &lt;&lt; ""; 函数的末尾添加一些cout &lt;&lt; ""; 的内容,它会按预期完成,而无需SIGSEGV。我完全被这件事难住了,希望你们至少能告诉我为什么会发生这种情况。如有必要,我会在Box::Print 的末尾加上cout &lt;&lt; "",但我真的更愿意处理这个错误。谢谢!

【问题讨论】:

  • 启用编译器警告(例如使用-Wall),您会立即发现问题。

标签: c++ linux c++11 segmentation-fault


【解决方案1】:

您忘记了operator 中的返回语句。在 Java 中,它甚至无法编译,但 C++ 更“宽松”,这意味着您可以使用 UB。

正如@Eichhörnchen 在评论中提到的,在处理 C++ 时启用编译器警告是必须的。

【讨论】:

  • 我觉得自己很愚蠢...感谢您注意到我的愚蠢错误
猜你喜欢
  • 2017-01-18
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2011-08-11
  • 2015-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多