2014-11-07 21 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