我正在尝试通过审核Coursera课程来完善我的C ++,但不确定如何使数组动态变化。
我首先声明一个名为HexTiles的类:
class HexTile {
public:
HexTile() :x(0), y(0), c(Color::NONE) {} //Default constructor for (0,0), blank tile
HexTile(int x_input, int y_input, Color c_input = Color::NONE) : x(x_input), y(y_input), c(c_input) {
/* Make sure the input coordinates are in range */
assert(x >= 0 && x < x_max);
assert(y >= 0 && y < y_max);
}
~HexTile() { delete this; } //Destructor
friend ostream& operator << (ostream& out, HexTile& hex);
void ChangeColor(Color c_input) { c = c_input; }
Color GetColor(void) { return c; }
private:
int x, y; //Coordinates
Color c; //Shows which player owns the tile
};
这里没有什么特别令人惊讶的。
然后我声明一个HexTables类,该类将一堆hextiles映射到一个数组:
class HexTable {
public:
HexTable(); //Default constructor
HexTable(int x_width, int y_width); //Constructor for custom dimensions
~HexTable() {
delete[] hex_array;
delete this;
} //Destructor
friend ostream& operator<<(ostream& out, HexTable& table);
void SetTableSize(int i) { x_width = i; y_width = i; }
void PlayTile(int x, int y, Color c) { hex_array[x][y]->ChangeColor(c); }
/* Make sure x and y are both within range */
bool isLegal(int x, int y) { return (x >= 0 && x < x_max) && (y >= 0 && y < y_max && hex_array[x][y]->GetColor() == Color::NONE); }
private:
int x_width, y_width;
HexTile* hex_array[x_max][y_max];
};
HexTable构造函数创建一堆HexTiles,并将它们放置在数组中。
HexTable::HexTable(){
x_width = x_max;
y_width = y_max;
/* Nested for loop to initialize all hex tiles */
for (int i=0; i<x_width; i++) {
for (int j = 0; j < y_width; j++) {
HexTile* p_hex = new HexTile(i,j); //Declare a new hextile at coordinates (i,j) and assign Color BLANK
hex_array[i][j] = p_hex; //Assign hex_array with p_hex pointer
}
}
}
它当前有效,但是我不喜欢将大小固定为[x_max] x [y_max],它们是固定的全局常量。我想使表大小动态化。我想到了把戏
HexTile** hex_array = new HexTile*[x_width];
for(int i=0; i<x_width;i++)
hex_array[i] = new HexTile[y_width];
但是会占用我通过数组查找[x] [y]查找hex_array的能力。任何专家都知道该怎么办?谢谢。