【问题标题】:Delaying array size in class definition in C++?在 C++ 中的类定义中延迟数组大小?
【发布时间】:2009-03-05 06:10:25
【问题描述】:

有没有办法延迟定义数组的大小,直到类方法或构造函数?

我的想法可能看起来像这样,这(当然)不起作用:

class Test
{
    private:
    int _array[][];

    public:
    Test::Test(int width, int height);
};

Test::Test(int width, int height)
{
    _array[width][height];
}

【问题讨论】:

    标签: c++ arrays size delay


    【解决方案1】:

    Daniel 所说的是,当调用 Test (width, height) 方法时,您需要为数组动态分配内存。

    你会像这样声明你的二维(假设是整数数组):

    int ** _array;
    

    然后在您的 Test 方法中,您需要首先分配指针数组,然后为每个指针分配一个整数数组:

    _array = new  *int [height];
    for (int i = 0; i < height; i++)
    {
        _array [i] = new int[width];
    }
    

    然后当对象被释放时,你需要显式删除你分配的内存。

    for (int i = 0; i < height; i++)
    {
        delete [] _array[i];
        _array [i] = NULL;
    }
    delete [] _array;
    _array = NULL;
    

    【讨论】:

    • 可以添加指针数组分配:_array = new int[height];支持提供来源!
    • 糟糕。谢谢丹尼尔。我忘了补充:)。干杯。
    • 手动数组管理的问题在于您需要创建自己的复制构造函数/操作符 = 或使类显式不可复制以防止将来出现问题
    • 我意识到这是几年后的事了,但我只想指出(因为我花了大约半个小时的谷歌搜索才弄明白:P)那个“_array = new *int [height ]" 应该是 " _array = new int*[height]' " 否则你会遇到编译器错误(使用 -W -Wextra -Wall -pedantic)。 :)
    【解决方案2】:

    矢量是你最好的朋友

    class Test
    {
        private:
        vector<vector<int> > _array;
    
        public:
        Test(int width, int height) :
            _array(width,vector<int>(height,0))
        {
        }
    };
    

    【讨论】:

    • Artyom 是绝对正确的。为自己省去一大堆痛苦:)。不过,我想了解基本原理是件好事。
    • 在数据结构方面,看起来向量在结构上仍然是一个数组,但包装在一个类中。是吗?
    • 是的,我认为大多数矢量实现都在“幕后”使用数组。您还可以使用数组运算符来操作向量。
    • 实际上一个向量必须使用一个数组来存储数据。标准规定向量中的元素是连续的。
    【解决方案3】:

    我认为是时候查找新/删除运算符了。

    鉴于这是一个多维数组,您将不得不在执行过程中循环调用“new”(同样不要忘记:delete)。

    虽然我相信很多人会建议使用具有宽度*高度元素的一维数组。

    【讨论】:

      【解决方案4】:

      (几个月后)可以使用模板,如下所示:

      // array2.c
      // http://www.boost.org/doc/libs/1_39_0/libs/multi_array/doc/user.html
      // is professional, this just shows the principle
      
      #include <assert.h>
      
      template<int M, int N>
      class Array2 {
      public:
          int a[M][N];  // vla, var-len array, on the stack -- works in gcc, C99, but not all
      
          int* operator[] ( int j )
          {
              assert( 0 <= j && j < M );
              return a[j];
          }
      
      };
      
      int main( int argc, char* argv[] )
      {
          Array2<10, 20> a;
          for( int j = 0; j < 10; j ++ )
          for( int k = 0; k < 20; k ++ )
              a[j][k] = 0;
      
          int* failassert = a[10];
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多