簡體   English   中英

C ++數組構造函數

[英]C++ Array 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];

};

據我所知,在C ++中無法在如上所述的Constructor中創建數組。 另外,可以在構造函數塊中按以下方式初始化數組成員。

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或第三方庫。

數組-比C ++本身更老的概念,直接繼承自C-確實沒有可用的構造函數,正如您基本上注意到的那樣。 有跡象表明,留給你給你提怪異的限制少的解決方法(無標准庫?!?!?) -你可以有a是一個指針到C而不是C數組,分配原始內存吧,然后使用“ placement new”初始化每個成員(至少可以解決C沒有默認構造函數的問題)。

您可以創建一個類來包裝數組並根據需要進行構造。 這是一個開始; 除了您看到的內容之外,此代碼未經測試。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM