2011-05-14 77 views
4

我在向量中嵌套向量的問題,相當於在C中的二維數組。我嘗試了代碼演示這張貼在衆多的網站,無濟於事。錯誤嵌套向量<>向量<>

class Board 
{ 
    public: 
     vector< vector<Cell> > boardVect; //Decalre the parent vector as a memebr of the Board class  

     Board() 
     { 
      boardVect(3, vector<Cell>(3)); //Populate the vector with 3 sets of cell vectors, which contain 3 cells each, effectivly creating a 3x3 grid. 

     } 
}; 

當我嘗試編譯,我收到此錯誤:

F:\ main.cpp中| 52 |錯誤:不對應的呼叫「(標準::矢量>)(INT,STD ::向量)」

52號線:boardVect(3, vector<Cell>(3));

與3矢量類構建親代載體時,我得到一個錯誤的錯誤?

回答

12

您需要使用,以呼籲你的類的成員構造函數初始化列表,即:

Board() 
    :boardVect(3, vector<Cell>(3)) 
{} 

一旦你進入構造函數體,爲時已​​晚,所有成員已經構建好了,只能調用非構造函數成員函數。你當然可以這樣做:

Board() 
{ 
    boardVect = vector<vector<Cell> >(3, vector<Cell>(3)); 
} 

但是初始化列表是首選。

+0

是的,那是我的問題,謝謝!我正在使用初始化列表;但我記得用於創建對象的非構造函數。 – dymk 2011-05-14 01:22:38

相關問題