如何設置一個類,我可以擁有一個私有二維數組,它的大小由通過構造函數傳入的變量來確定?在構造上創建一個長度可變的二維數組
我已經試過這樣:
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 first
和array 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’
。
我在做什麼錯?
編輯: 我寧願避免使用矢量,因爲我還沒有在這門課程中「學習」它們。 (據我學習,我的意思是我知道如何使用它們,但教授沒有討論過它們,也不喜歡我們使用外部知識)
建議 - 不要命名變量'map'。 – PaulMcKenzie 2014-11-07 01:12:31
C風格的陣列非常挑剔,這就是爲什麼我們建議人們不要使用它們。如果在編譯時確實知道寬度和高度,則可以使數組工作。 – 2014-11-07 01:27:55
爲什麼我不應該將它命名爲地圖?尺寸在施工中已知,而不是在以前。 – Malfist 2014-11-07 01:33:41