C ++数组构造函数

时间:2009-12-22 06:58:36

标签: c++ arrays constructor

我只是想知道,是否可以在类构造时立即创建类的数组成员:

class C
{
      public:
          C(int a) : i(a) {}

      private:
          int i;
};

class D
{
 public:
        D() : a(5, 8) {}
        D(int m, int n) : a(m,n) {}

     private:
     C a[2];

};

就我用Google搜索而言,构造函数中的数组创建(如上所述)在C ++中是不可能的。或者,可以在构造函数块中初始化数组成员,如下所示。

class D
    {
     public:
         D() { 
               a[0] = 5;
               a[1] = 8; 
             }
         D(int m, int n) { 
                           a[0] = m;
                           a[1] = n; 
                         }
         private:
         C a[2];

    };

但是,它不再是一个数组创建,而是数组赋值。数组元素由编译器通过其默认构造函数自动创建,随后将它们手动分配给C'tor块中的特定值。什么令人讨厌;对于这种解决方法,C类必须提供默认的构造函数。

有没有人知道哪些可以帮助我在构建时创建数组成员。我知道使用std :: vector可能是一个解决方案,但由于项目条件的原因,我不允许使用任何标准,Boost或第三方库。

2 个答案:

答案 0 :(得分:5)

数组 - 一个比C ++本身更早的概念,直接从C继承 - 并没有真正有可用的构造函数,因为你基本上都注意到了。鉴于您提到的奇怪约束(没有标准库?!?!?),您可能有很少的解决方法 - 您可以让a成为C的指针比一个C数组,为它分配原始内存,然后使用“placement new”初始化每个成员(至少解决了C没有默认构造函数的问题)。

答案 1 :(得分:1)

您可以创建一个类来包装数组并根据需要构造。这是一个开始;除了你所看到的,这段代码是未经测试的。

#include <iostream>
using namespace std;

template< class T, int N >
struct constructed_array {
        char storage[ sizeof( T[N] ) ]; // careful about alignment
        template< class I >
        constructed_array( I first ) {
                for ( int i = 0; i < N; ++ i, ++ first ) {
                        new( &get()[i] ) T( *first );
                }
        }
        T *get() const { return reinterpret_cast< T const* >( storage ); }
        T *get() { return reinterpret_cast< T * >( storage ); }
        operator T *() const { return get(); }
        operator T *() { return get(); }
};

char const *message[] = { "hello", ", ", "world!" };

int main( int argc, char ** argv ) {
        constructed_array< string, 3 > a( message );
        for ( int i = 0; i < 3; ++ i ) {
                cerr << a[i];
        }
        cerr << endl;
        return 0;
}