繁体   English   中英

使用重载的insertopm(<<)运算符时,为什么会得到SIGSEGV?

[英]Why do I get a SIGSEGV when I use my overloaded insertopm (<<) operator?

我正在上C ++类,对于最近的工作,我必须创建一个Box类。 总体而言,任务实际上是在公园散步,但是我遇到了本应创建的重载插入运算符的问题。 插入操作符在box.h声明,并在box.cpp定义,这是标准操作。 Box类中,我有一个print(std::ostream &) const函数。 重载的插入运算符所做的全部工作就是调用std::ostream &提供给该运算符的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 << "";的曲调中添加一些内容cout << ""; Box::print函数的末尾,它会按预期完成,而没有SIGSEGV。 我对此完全感到困惑,并希望你们至少可以帮我弄清楚为什么会这样。 如有必要,我将在Box::Print的末尾使用cout << ""将其打开,但我真的更喜欢处理此错误。 谢谢!

您忘记了operator的return语句。 在Java中,它甚至不会编译,但是C ++更“宽松”,这意味着您可以得到UB。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM