繁体   English   中英

如何在 C++ 构造函数中初始化多维数组

[英]How to initialize a multi-dimensional array in a C++ constructor

我有一个 class 包含一些多维 arrays。 我正在尝试在构造函数中初始化这些 arrays,但我无法弄清楚如何去做。 该数组始终具有固定大小。 这是我到目前为止所拥有的:

class foo {
  private: 
    int* matrix; //a 10x10 array

  public:
    foo();

  foo:foo() {
    matrix = new int[10][10]; //throws error
  }

我得到的错误是:

cannot convert `int (*)[10]' to `int*' in assignment 

我怎样才能做到这一点? 最好,我希望数组默认为全 0 的 10x10 数组。

#include <memory.h>
class foo
{
    public:
        foo()
        {
            memset(&matrix, 100*sizeof(int), 0);
        }
    private:
        int matrix[10][10];
};

也就是说,如果您没有将自己绑定到使用指针来执行此操作(否则您可以只将指针传递给 memset,而不是对数组的引用)。

做这个:

int **matrix; //note two '**'

//allocation
matrix = new int*[row]; //in your case, row = 10. also note single '*'
for(int i = 0 ; i < row ; ++i)
   matrix[i] = new int[col]; //in your case, col = 10


 //deallocation
 for(int i = 0 ; i < row ; ++i)
   delete [] matrix[i];
 delete matrix;

建议:您可以使用std::vector代替使用int**

 std::vector<std::vector<int> > matrix;

//then in the constructor initialization list
foo() : matrix(10, std::vector<int>(10))
{  // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this is called initialization list
}

如果您遵循这种方法,则无需在代码中使用newdelete 此外,矩阵的大小为10x10 您可以将它们作为matrix[i][j]访问,其中0<=i<100<=j<10 还要注意, matrix中的所有元素都用0初始化。

尝试这个:

class foo
{
private:
  int **matrix;

public:
  foo()
  {
    matrix = new int*[10];
    for (size_t i=0; i<10; ++i) 
      matrix[i] = new int[10];
  }

  virtual ~foo()
  {
    for (size_t i=0; i<10; ++i)
      delete[] matrix[i];
    delete[] matrix;
  }
};

在您的编译器支持 C++0x 统一初始化之前,如果您想在初始化列表中这样做,恐怕您必须分别初始化数组中的每个条目。

但是,您可以做的是不初始化而是分配给构造函数内的数组(简单的 for 循环)。

在您的代码中,您有一个指针,而不是一个数组。 如果您需要为您处理 memory 管理的元素集合,您可能想要使用 std::vector 。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM