저는 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);
}
이제 여기에 정말 이상한 부분이 있습니다. Box::print
함수의 끝에 cout << "";
의 곡에 뭔가를 추가하면 SIGSEGV없이 의도 한대로 완료됩니다. 나는 이것으로 완전히 완전히 곤란을 겪었고, 여러분이 적어도 이것이 왜 일어나고 있는지에 대해 알 수 있기를 바랬습니다. 필요한 경우, Box::Print
끝에 cout << ""
으로 바꾸 겠지만이 오류를 처리하는 것이 좋습니다. 감사!
컴파일러 경고 (예 :'-Wall')를 사용하면 문제가 즉시 발생합니다. – user4407569