我正在学习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 << ""
来打开它,但我真的更愿意处理这个错误。谢谢!
启用编译器警告(例如使用'-Wall'),您将立即发现问题。 – user4407569