这是我为学校工作的一些代码。当我运行它时,我得到一个bad_alloc错误。它最有可能出现在类定义中的某个地方,但我尝试过的任何工作都没有。有人能告诉我哪里发生了错误的分配?
#include <iostream>
#include <vector>
using namespace std;
enum Dir
{
LEFT = 1,
RIGHT = 1 << 1,
UP = 1 << 2,
DOWN = 1 << 3,
};
class Cell
{
friend class Board;
int row_, col_;
bool visited_;
unsigned int walls_;
Cell* up_;
Cell* down_;
Cell* left_;
Cell* right_;
Cell& set_up(Cell *up)
{
up_ = up;
return *this;
}
Cell& set_down(Cell *down)
{
down_ = down;
return *this;
}
Cell& set_left(Cell *left)
{
left_ = left;
return *this;
}
Cell& set_right(Cell *right)
{
right_ = right;
return *this;
}
public:
Cell( int row = -1, int col = -1)
:row_(row), col_(col), visited_(false), walls_(LEFT | RIGHT | UP | DOWN){}
bool visited() const
{
return visited_;
}
bool hasWall(Dir d) const
{
return walls_ & d;
}
void drill(Dir d)
{
walls_ &= ~d;
}
void draw(int step = 20) const
{
cout << col_*step << " " << row_*step << " " << "moveto" << endl;
cout << step << " " << 0 << " " << (hasWall(DOWN)?"rlineto":"rmoveto") << endl;
cout << 0 << " " << step << (hasWall(RIGHT)?"rlineto":"rmoveto") << endl;
cout << -step << " " << 0 << " " << (hasWall(UP)?"rlineto":"rmoveto") << endl;
cout << 0 << " " << -step << (hasWall(DOWN)?"rlineto":"rmoveto") << endl;
}
Cell* up() const
{
return up_;
}
Cell* down() const
{
return down_;
}
Cell* left() const
{
return left_;
}
Cell* right() const
{
return right_;
}
};
class Board
{
friend class Cell;
int rows_, cols_;
vector<Cell> cells_;
public:
Board(int rows, int cols)
: rows_(rows), cols_(cols)
{
for(int i = 0; i < rows_; i++)
for (int j = 0; i < cols_; j++)
cells_.push_back(Cell(i, j));
for (int i = 0; i < rows_ ; i++)
for(int j = 0; j < cols_; j++)
{
Cell& c = at(i, j);
if(i < rows_ - 1)
c.set_up(&at(i + 1 , j));
if(i > 0)
c.set_down(&at(i - 1 , j));
if(j > 0)
c.set_left(&at(i , j - 1));
if(j < cols_ - 1)
c.set_right(&at(i, j + 1));
}
}
Cell& at(int i, int j)
{
int index = i*cols_ + j;
return cells_[index];
}
const Cell& at(int i, int j) const
{
int index = i*cols_ + j;
return cells_[index];
}
void draw() const
{
cout << "newpath" << endl;
for (vector<Cell>::const_iterator it = cells_.begin(); it != cells_.end(); ++it)
{
(*it).Cell::draw();
}
cout << "stroke" << endl;
cout << "showpage" << endl;
}
};
int main()
{
Board b(5, 5);
Cell& c = b.at(2, 2);
c.drill(UP);
Cell* up = c.up();
up->drill(DOWN);
b.draw();
return 0;
}
答案 0 :(得分:1)
董事会构造函数 - 对于()你有错误的终止条件。应该有&#34; j&lt; COLS _&#34;而不是&#34; i&lt; COLS _&#34;