我参加了C ++课程,而对于我最近的任务,我必须创建一个Box
课程。总的来说,这项任务实际上是在公园里散步,但是我应该在我应该创建的重载插入算子上遇到一些麻烦。插入运算符在box.h
中声明,并在box.cpp
中定义,这是标准的。在Box
课程中,我有print(std::ostream &) const
个功能。所有重载的插入运算符都会调用提供给运算符的print
上的std::ostream &
函数。相关代码:
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。我完全被这完全困扰了,并希望你们至少可以告诉我为什么会发生这种情况。如有必要,我会在cout << ""
结束时将其与Box::Print
联系起来,但我更愿意处理此错误。谢谢!
答案 0 :(得分:1)
您忘记了operator
中的退货声明。在Java中,它甚至不会编译,但C ++更“宽容”,这意味着你会得到UB。
正如@Eichhörnchen在评论中提到的,在处理C ++时,启用编译器警告是必须的。