2009-12-22 89 views
5

我想知道,無論是類的一個陣列成員可以在類結構立即創建:C++數組構造

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++中不可能。或者,數組成員可以在構造函數塊內初始化,如下所示。

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

+1

你必須等待C++ 0x,它允許這個。 – 2009-12-22 07:40:05

回答

5

數組 - 一個比C++本身更早的概念,直接從C繼承而來 - 實際上並沒有可用的構造函數,因爲你基本上都注意到了。由於你提到的怪異約束(沒有標準庫?!?!?),有幾個解決方法留給你 - 你可以將指針指向而不是C數組,分配原始內存然後使用「放置新的」初始化每個成員(圍繞C沒有缺省構造函數的問題工作,至少)。

+1

當尺寸固定時,C數組通常優於矢量; C++向量也沒有「從內聯數據構造」功能(儘管C++ 0x的確如上所述,並且可以聲明常量數組並從迭代器初始化)。 – Potatoswatter 2009-12-22 08:16:01

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

只是說':boost :: array http://www.boost.org/doc/libs/1_41_0/doc/html/boost/array.html – sbk 2009-12-22 10:13:13

+0

我完全同意。 – Potatoswatter 2009-12-22 17:02:27