首先,我不明白Queen
和Piece
之間的依賴關係派生類,所以我想這Piece
超型Queen
和分配Piece * mx = new Queen();
是正確的。
要修正類型不匹配的明顯的問題,你可以改變你的
void changeToQueen(Piece* mx)
到
void changeToQueen(Piece* mx[7][7])
和不斷變化的環境7(for (int i = 0; i < 7; i++)
)或矩陣的大小8 x 8
(與相同的循環),這將工作。
但我的建議是想一想存儲數據的方法。 也許你會需要建立大小從7x7的不同的矩陣,那麼看看下面的例子,其中動態內存用於存儲矩陣(在這個例子中只使用Queen
):
void changeToQueen(Queen*** &mx, int size)
{
mx = new Queen**[size]; // allocation of memory for pointers of the first level
for (int i = 0; i < size; i++)
{
mx[i] = new Queen*[size]; // allocation of memory for pointers of the second level
for (int j = 0; j < size; j++)
{
mx[i][j] = new Queen(); // allocation of memory for object
}
}
}
int main()
{
int m_size = 7;
Queen *** matrix = NULL; // now memory not allocated for matrix
changeToQueen(matrix, m_size);
return 0;
}
注:&
標誌在void changeToQueen(Queen*** &mx, int size)
允許改變指針Queen *** matrix;
裏面的功能changeToQueen
'void changeToQueen(Piece * mx [7] [7])' –
根據循環條件判斷,您需要'Piece * matrix [8] [8];'。 –
你有內存泄漏 –