代码之家  ›  专栏  ›  技术社区  ›  zaratustra

确定构造函数初始值设定项中的数组大小

  •  14
  • zaratustra  · 技术社区  · 16 年前

    在下面的代码中,我希望在调用类构造函数时将数组定义为大小为X的数组。我该怎么做?

    class Class
    {
    public:
      int array[];
      Class(int x) : ??? { }
    }
    
    11 回复  |  直到 6 年前
        1
  •  20
  •   jedwards    12 年前

    不能初始化具有非const维度的数组的大小,该维度不能在编译时计算(至少不在当前C++标准中,AFAIK)。

    我建议使用 std::vector<int> 而不是数组。它为大多数操作提供类似数组的语法。

        2
  •  44
  •   Jeff Diamond    12 年前

    你们这些人把这件事搞得太复杂了。当然,你可以在C++中做到这一点。为了提高效率,他可以使用普通阵列。矢量只有在他不知道数组的最终大小时才有意义,也就是说,它需要随着时间的推移而增长。

    如果您知道数组的大小比链中的高一级,那么模板类是最简单的,因为没有动态分配,也没有内存泄漏的可能性:

    template < int ARRAY_LEN > // you can even set to a default value here of C++'11
    
    class MyClass
      {   
      int array[ARRAY_LEN]; // Don't need to alloc or dealloc in structure!  Works like you imagine!   
      }
    
    // Then you set the length of each object where you declare the object, e.g.
    
    MyClass<1024> instance; // But only works for constant values, i.e. known to compiler
    

    如果您不知道在您声明对象的地方的长度,或者您想用不同的长度重用同一个对象,或者您必须接受一个未知的长度,那么您需要在构造函数中分配它并在析构函数中释放它…(理论上总是检查以确保它工作…)

    class MyClass
      {
      int *array;
    
      MyClass(int len) { array = calloc(sizeof(int), len); assert(array); }   
      ~MyClass() { free(array); array = NULL; } // DON'T FORGET TO FREE UP SPACE!
      }
    
        3
  •  11
  •   John Dibling    16 年前

    使用新操作员:

    class Class
    {
       int* array;
       Class(int x) : array(new int[x]) {};
    };
    
        4
  •  4
  •   AFoglia    14 年前

    我觉得做不到。至少不是你想要的方式。当大小来自动态信息(X)时,不能创建静态大小的数组(数组[])。

    您需要存储指向int的指针和大小,并重载复制构造函数、赋值运算符和析构函数来处理它,或者使用std::vector。

    class Class
    {
      ::std::vector<int> array;
      Class(int x) : array(x) { }
    };
    
        5
  •  4
  •   Miguel Leon    14 年前

    你难道不明白,没有必要使用向量,如果你想使用数组,这是一个效率问题,例如,空间小,没有复制时间(在这种情况下,如果处理得当,甚至不需要删除一个析构函数中的数组),等等,不管你有什么理由。

    正确答案是:(引用)

    class Class
    {
       int* array;
       Class(int x) : array(new int[x]) {};
    };
    

    不要试图强迫一个人使用非最佳的替代方法,否则你会混淆没有经验的程序员。

        6
  •  3
  •   user563910    14 年前

    抱歉弄脏了这根旧线。 实际上,有一种方法可以找出数组编译时间的大小。就像这样:

    #include <cstdlib>
    
    template<typename T>
        class Class
        {
            T* _Buffer;
    
            public:
            template<size_t SIZE>
                Class(T (&static_array)[SIZE])
                {
                    _Buffer = (T*)malloc(sizeof(T) * SIZE);
    
                    memcpy(_Buffer, static_array, sizeof(T) * SIZE);
                }
    
                ~Class()
                {
                    if(_Buffer)
                    {
                        free(_Buffer);
                        _Buffer = NULL;
                    }
                }
        };
    
    int main()
    {
        int int_array[32];
        Class<int> c = Class<int>(int_array);
    
        return 0;
    }
    

    或者,如果您不喜欢malloc/new,那么您可以创建一个大小模板化的类。不过,我并不推荐它,而且它的语法也很难看。

    #include <cstdio>
    
    template<typename T, size_t SIZE>
        class Class
        {
            private:
                T _Array[sz];
            public:
                Class(T (&static_array)[SIZE])
                {
                    memcpy(_Array, static_array, sizeof(T) * SIZE);
                }
        };
    
    int main()
    {
        char int_array[32];
        Class<char, sizeof(int_array)> c = Class<char, sizeof(int_array)>(int_array);
        return 0;
    }
    

    无论如何,我希望这是有帮助的:)

        7
  •  1
  •   Brian    16 年前

    与其使用原始数组,不如使用向量。

    class SomeType {
      vector<int> v;
      SomeType(size_t x): v(x) {}
    };
    

    使用向量可以在遇到异常时自动提供泄漏保护,而且与原始数组相比还有许多其他好处。

        8
  •  0
  •   jwfearn    16 年前

    你不能在C++中使用它:使用一个STD::向量代替:

    #include <vector>
    
    struct A {
       std::vector <int> vec; 
       A( int size ) : vec( size ) {
       }
    };
    
        9
  •  0
  •   Community CDub    7 年前

    将数组声明为指针。稍后可以通过new在初始值设定项列表中初始化它。

    对于未知的大小最好使用向量。

    你可能想看看 this question 以及可变长度数组。

        10
  •  0
  •   Loki Astari    16 年前

    两种选择:

    使用std::vector。这样可以方便地重新调整数组的大小。
    使用std::tr1::array。这是静态大小。

    这两者都可以在构造函数初始值设定项列表中正确初始化。

        11
  •  0
  •   Sherazi Rajput    6 年前

    我也有同样的问题,我用这种方法解决了它

    class example
    {
      int *array;
    
      example (int size)
      {
        array = new int[size];
      }
    }