2016-05-30 49 views
0

我有一個很大的問題,我想把對象的矩陣指針放到一個函數中,但我不知道如何做到這一點,我使用它們的對象來自派生類。這是我的代碼的一個例子。注:類件是一個基類和類皇后是件如何在C++中返回一個矩陣指針?

#include "Queen.h" 

void changeToQueen(Piece* mx) 
{ 
    for (int i = 0; i < 8; i++) 
    { 
     for (int j = 0; j < 8; j++) 
     { 
      mx[i][j] = new Queen(); 
     } 
    } 

} 
int main() 
{ 
    Piece * matrix[7][7]; 
    changeToQueen(matrix); // this fails 
    return 0; 
} 
+1

'void changeToQueen(Piece * mx [7] [7])' –

+2

根據循環條件判斷,您需要'Piece * matrix [8] [8];'。 –

+0

你有內存泄漏 –

回答

0

你可以改變輸入參數爲void changeToQueen(Piece * mx[7][7])

或者您可以將輸入參數更改爲void changeToQueen(Piece** mx)。 賦值運算符更改爲mx[7*i + j] = new Queen();並且在第一元件通過作爲輸入changeToQueen(&(matrix[0][0]));

之所以都工作是因爲多維數組元素被連續存儲在存儲器中。所以你需要的是一個指向第一個元素的指針。

這兩種解決方案都有點缺陷,因爲如果您需要更改矩陣的尺寸,則必須稍微更改代碼。將原型更改爲void changeToQueen(Piece** mx, size_t width, size_t height)將對未來有所幫助。

0

首先,我不明白QueenPiece之間的依賴關係派生類,所以我想這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

0

或者這可能是處理事情

template <unsigned int rows, unsigned int columns> 
class Board 
{ 
    public: 
     Board() {} 

     void changeToQueen() 
     { 
      for (unsigned int y = 0 ; y < rows ; ++y) 
      { 
       for (unsigned int x = 0 ; x < columns ; ++x) 
       { _pieces[y][x] = Queen(); } 
      } 
     } 

     Piece &at(unsigned int row, unsigned int column) 
     { return _pieces[row][column]; } // you should check for out of range 
     // you could either have a default null value for Piece to return, or throw an exception 

    private: 
     Piece _pieces[rows][columns]; 
}; 

int main() 
{ 
    Board<8,8> board; 

    board.changeToQueen(); 
    // return 0; // this is not mandatory in c++ 
} 

所以,是的,沒有指針幾乎無後顧之憂的方式;)

你仍然想指針?呃...好吧,也許你可以這樣做:Piece *_pieces[rows][columns];,我不知道你真的需要它,但我不知道它會修改你現有的代碼做多少。