所以我正在用 C++ 开发简单的控制台战舰。我有一个像这样的船:
class Ship {
public:
virtual void draw(int x, int y){}
virtual void shoot(int x, int y){}
virtual bool isDead(){};
};
以及从它继承的两个类(水平船和垂直船)。所以一个垂直样本是:
class VertShip : public Ship{
private:
int x, y, shipSize;
char deck[4];
public:
VertShip(int x, int y, int shipSize) : x(x), y(y), shipSize(shipSize) {
for(int i=0; i<shipSize; ++i)
{
deck[i] = '_';
}
}
virtual void draw(int x, int y){
cout << deck[y - this->y];
}
virtual void shoot(int x, int y){
deck[y - this->y] = 'T';
--shipSize;
}
virtual bool isDead()
{
if(this->shipSize) return 0;
return 1;
}
};
所以只有我甲板上的每个单元格都在对象内部表示。当有人调用 Board 类的 fire() 方法并成功击中船时,Shoot() 运行,并且 draw() 向 drawBoard() 方法提供有关船甲板给定单元的信息。此外,ships[] 是一个指向 ship 对象的指针数组。所以到目前为止一切正常 - 问题出在 Board::fire() 上:
void Board::fire(int w, int k){
if(mapOfCells[w][k]>=0)
ships[mapOfCells[w][k]]->shoot(w,k);
//if(ships[mapOfCells[w][k]]->isDead()) cout<<"The ship has drown.\n";
else
mapOfCells[w][k]=-2;
}
一旦我取消注释 if,奇怪的行为就开始了。它给了我不正确的信息(声称其中有船的单元格是空的,反之亦然)并且游戏在三枪后崩溃。但是,如果我对此发表评论,它会完美运行-只是不会让您知道您是否完全沉没了一艘船。
它出什么问题了?如果我在这个中做一些恶意的事情吗?遗憾的是,我无法提供一个简短的、可编译的源代码,因为没有大多数类和方法,这个游戏根本无法运行,而且其中有很多。