2016-10-05 21 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

我覺得很蠢...謝謝你注意我的愚蠢的錯誤 –