2014-11-07 20 views
0

如何設置一個類,我可以擁有一個私有二維數組,它的大小由通過構造函數傳入的變量來確定?在構造上創建一個長度可變的二維數組

我已經試過這樣:

class World { 
    private: 
     const int WIDTH; 
     const int HEIGHT; 
     bool map[][]; 
    public: 
     World(const int MAX_X, const int MAX_Y) : WIDTH(MAX_X), HEIGHT(MAX_Y) { 
      map = new bool[WIDTH][HEIGHT]; 
     } 
}; 

,但我得到一個關於如何declaration of ‘map’ as multidimensional array must have bounds for all dimensions except the firstarray size in operator new must be constant即使它是一堆錯誤。

我也嘗試過這種方式,但它沒有工作,要麼:

class World { 
    private: 
     const int WIDTH; 
     const int HEIGHT; 
     bool map[WIDTH][HEIGHT]; 
    public: 
     World(const int MAX_X, const int MAX_Y) : WIDTH(MAX_X), HEIGHT(MAX_Y) { 
      //map = new bool[WIDTH][HEIGHT]; 
     } 
}; 

我上const int WIDTH線和在地圖上聲明行相當無用error: from this location一個invalid use of non-static data member ‘World::WIDTH’

我在做什麼錯?

編輯: 我寧願避免使用矢量,因爲我還沒有在這門課程中「學習」它們。 (據我學習,我的意思是我知道如何使用它們,但教授沒有討論過它們,也不喜歡我們使用外部知識)

+0

建議 - 不要命名變量'map'。 – PaulMcKenzie 2014-11-07 01:12:31

+0

C風格的陣列非常挑剔,這就是爲什麼我們建議人們不要使用它們。如果在編譯時確實知道寬度和高度,則可以使數組工作。 – 2014-11-07 01:27:55

+0

爲什麼我不應該將它命名爲地圖?尺寸在施工中已知,而不是在以前。 – Malfist 2014-11-07 01:33:41

回答

1

你可以使用一個向量。

class World 
{ 
    typedef std::vector<bool> Tiles; 
    typedef std::vector<Tiles> WorldMap; 

    World(unsigned int width, unsigned int height) 
    { 
    for (unsigned int i = 0; i < width; i++) 
    { 
     m_map.push_back(Tiles(height)); 
    } 
    } 

private: 
    WorldMap m_map;  
}; 

或者你可以使用模板,如果你知道編譯時的世界大小。

template <unsigned int Width, unsigned int Height> 
class World 
{ 
private: 
    bool m_map[Width][Height]; 
}; 

或者你可以使用原始指針,因爲2d數組實際上只是指向數組的指針數組。

class World 
{ 
    // Make sure you free this memory. 
    World(unsigned int width, unsigned int height) 
    { 
    m_map = new bool*[width]; 
    for(unsigned int i = 0; i < height; ++i) 
    { 
     m_map[i] = new bool[width]; 
    } 
    } 

private: 
    bool** m_map; 
}; 

我建議使用前兩個選項之一。

0

數組的大小必須在編譯時確定,而不是在運行時確定。

如果您想要運行時調整大小,您應該選擇其他容器。可能:

- std::vector<bool> // and then simulate a 2d array using indexing 
- std::vector<std::vector<bool>> // if you insist on using [][] syntax 
+0

爲了澄清索引,'[x + y * x_size]'得到索引。 – 2014-11-07 01:28:32

+0

我已經使用標準數組完成了「使用索引來模擬2d數組」,但我寧願按照「正確的方式」來使用實際的2d數組。我對C++排除數組運行時確定的大小感到困惑 – Malfist 2014-11-07 01:38:38

+0

@Malfist - 問題在於,按照您的方式聲明數組需要在編譯時提供大小的堆棧內存分配。 C++不會'排除'在運行時構建2d數組的能力,只需要以不同的方式來完成。 – Aesthete 2014-11-07 02:34:08