【问题标题】:How to initialize a multi-dimensional array in a C++ constructor如何在 C++ 构造函数中初始化多维数组
【发布时间】:2011-04-30 04:59:52
【问题描述】:

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

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 数组。

【问题讨论】:

    标签: c++ arrays


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

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

    【讨论】:

    • memset(matrix, sizeof matrix / sizeof **matrix, 0);std::fill_n( &amp;matrix[0][0], sizeof matrix / sizeof **matrix, 0 );
    【解决方案2】:

    这样做:

    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;
    

    建议:不要使用int**,您可以使用std::vector作为:

     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&lt;=i&lt;100&lt;=j&lt;10;还要注意matrix 中的所有元素都是用0 初始化的。

    【讨论】:

      【解决方案3】:

      试试这个:

      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;
        }
      };

      【讨论】:

        【解决方案4】:

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

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

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

        【讨论】:

          猜你喜欢
          • 2014-05-23
          • 2015-07-13
          • 2021-07-16
          • 2022-01-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-04
          相关资源
          最近更新 更多