Aus*_*ore 1 c++ segmentation-fault
我正在使用gcc编译程序,当我运行时,a.out
我收到此错误:
分段错误:11
我认为这与它有关Board::display
,但我没有看到它有什么问题..
#include <iostream>
using namespace std;
const bool WHITE = 0;
const bool BLACK = 1;
//-----------------------------
class Piece
{
public:
// constructors
Piece();
Piece(bool color);
// functions
char getColor() const {return color; }
bool getSymbol() const {return symbol;}
protected:
bool color;
char symbol;
};
ostream& operator << (ostream& out, const Piece & piece)
{
out << piece.getSymbol();
return out;
}
Piece::Piece() { }
Piece::Piece(bool color)
{
this->color = color;
}
//-----------------------------
class King : public Piece
{
public:
King(bool color);
};
King::King(bool color) : Piece(color)
{
this->symbol = 'K';
}
//-----------------------------
class Tile
{
public:
// constructors/destructors
Tile();
Tile(Piece piece, int row, int col);
// functions
bool getColor() const {return color;}
void display();
private:
Piece piece;
int row, col;
bool color;
};
Tile::Tile() { }
Tile::Tile(Piece piece, int row, int col)
{
this->row = row;
this->col = col;
}
void Tile::display()
{
if (getColor() == BLACK)
{
if (piece.getColor() == BLACK)
cout << "\E[30;47m " << piece << " \E[0m";
else
cout << "\E[37;47m " << piece << " \E[0m";
}
else
{
if (piece.getColor() == BLACK)
cout << "\E[30;41m " << piece << " \E[0m";
else
cout << "\E[37;41m " << piece << " \E[0m";
}
}
//---------------------------
class Board
{
public:
// constructor
Board();
// functions
void display();
private:
Tile *tiles[8][8];
};
Board::Board()
{
for (int r = 0; r < 8; r++)
for(int c = 8; c < 8; c++)
tiles[r][c] = new Tile(King(BLACK), r, c);
}
void Board::display()
{
for (int r = 7; r >= 0; r--)
{
for(int c = 7; c >= 0; c--)
tiles[r][c]->display();
cout << endl;
}
}
//---------------------------
int main()
{
Board board;
board.display();
}
Run Code Online (Sandbox Code Playgroud)
In Board::display()
,and r++
be r--
和ditto for c++
.
如果(像我一样)你更喜欢数组索引的无符号变量,你可以像这样编写循环:
for (std::size_t i = 0; i != N; ++i)
{
array[N - 1 - i] = something();
}
Run Code Online (Sandbox Code Playgroud)
或者,如果你发现这很麻烦,但你仍然真的不喜欢<=
并且更喜欢迭代器风格的"非等于"终止(像我一样),你可以坚持使用无符号类型并说:
for (std::size_t i = N; i != 0; --i)
{
array[i - 1] = anotherthing();
}
Run Code Online (Sandbox Code Playgroud)
您的下一个错误是按基数的值存储多态对象.那不行!相反,您可能希望保存指针(或引用).在我们学习的时候,是时候学习构造函数初始化列表了:
class Tile
{
Piece * piece; // must be a polymorphic handle!
int row;
int col;
public:
Tile(Piece * p, int r, int c) : piece(p), row(r), col(c) { }
Tile() : piece(NULL), row(0), col(0) { }
};
Run Code Online (Sandbox Code Playgroud)
如果按值存储多态对象,则最终会对其进行切片.你可以通过Piece
抽象来节省自己的麻烦.
如您所见,您还应确保默认构造函数执行某些有用的操作.事实上,我认为默认构造函数实际上没有意义,你应该删除它.
最后,我应该补充一点,Tile
类设计是一个可怕的问题,因为你不管理Piece
目前只是泄漏的对象的生命周期.如果你要管理它们,你需要delete
在析构函数中使用Tile
,但是你需要实现三条规则,现在你意识到Piece
需要一个虚拟析构函数......
我意识到这将成为"如何做C++"的完整章节,所以我现在就停止了.我想我们推荐的名单上有几本好书; 请咨询那些.