2016-10-05 20 views
0

我正在学习C++类,对于我最近的作业,我必须创建一个Box类。总的来说,这个任务实际上是在公园里散步,但我在我应该创建的重载插入算子方面遇到了一些麻烦。按照标准,插入运算符在box.h中声明,并在box.cpp中定义。在Box类中,我有一个print(std::ostream &) const函数。所有重载插入操作符都会调用提供给操作员的std::ostream &上的print函数。相关代码:当我使用我的重载insertopm(<<)运算符时,为什么会得到SIGSEGV?

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 << "";Box::print函数的末尾添加一些内容,它会按预期完成,而不使用SIGSEGV。我完全被这个难住了,希望你们至少可以告诉我为什么会发生这种事。如果有必要的话,我会在Box::Print的末尾用cout << ""来打开它,但我真的更愿意处理这个错误。谢谢!

+2

启用编译器警告(例如使用'-Wall'),您将立即发现问题。 – user4407569

回答

1

您忘记了您的operator中的退货声明。在Java中,它甚至不会编译,但C++更“宽容”,意味着你得到UB。

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

+0

我觉得很蠢...谢谢你注意我的愚蠢的错误 –