【发布时间】:2016-10-05 05:43:32
【问题描述】:
我正在学习 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 << ""; 的内容,它会按预期完成,而无需SIGSEGV。我完全被这件事难住了,希望你们至少能告诉我为什么会发生这种情况。如有必要,我会在Box::Print 的末尾加上cout << "",但我真的更愿意处理这个错误。谢谢!
【问题讨论】:
-
启用编译器警告(例如使用
-Wall),您会立即发现问题。
标签: c++ linux c++11 segmentation-fault