2011-05-26 39 views
8

結構的成員陣列如果我有:C++:動態地分配使用非默認的構造

struct a_struct 
{ 
    int an_int; 

    a_struct(int f) : an_int(f) {} 
    a_struct() : an_int(0) {} 
}; 

class a_class 
{ 
    a_struct * my_structs; 

    a_class() {...} 
}; 

我可以這樣做:

a_class() {my_structs = new a_struct(1)} 
//or 
a_class() {my_structs = new a_struct [10]} 

但我不能做:

a_class() {my_structs = new a_struct(1) [10]} 
//or 
a_class() {my_structs = new a_struct() [10]} 

是否有任何正確的語法來使其工作?或者一個簡單的解決方法?

回答

5

如果使用STL是一個選項,您可以使用std :: vector而不是動態數組。

認爲,這將工作:

std::vector<a_struct> my_structs; 

my_structs.assign(10, 1); 

如果不是,這應該:

my_structs.assign(10, a_struct(1)); 
+2

或者只是'的std ::矢量 my_structs(10,1 );' – Nemo 2011-05-27 00:23:33

0

你可以使用指針數組的指針。然後,您可以創建一個將舉行指向a_struct()數組,所以你可以在以後決定使用哪個構造:

class a_class { 
    a_struct ** my_structs; 

    a_class() { my_structs = new a_struct* [10]} 
    void foo() { 
     my_structs[0] = new a_struct(1); 
     my_structs[5] = new a_struct("some string and float constructor", 3.14); 
    } 
}; 
+0

這不允許你傳遞一個結構數組(或指向結構的指針,然後使用指針數學移動到數組的下一個元素)。 – iheanyi 2014-08-21 20:20:31

0

你不能直接做任何特定參數的構造函數。但是你可以做,

a_struct *my_struct[10] = {}; // create an array of pointers 

for (int i = 0; i < 10; i++) 
    my_struct[i] = new a_struct(i); // allocate using non-default constructor 

當你要去,解除分配內存

for (int i = 0; i < 10; i++) 
    delete my_struct[i] // de-allocate memory 

我建議使用std::vector容器,而不是通過此過程中去。

+1

在這種情況下,'std :: vector'的優點是所有'my_struct'都將在一個連續的內存塊中。 – Xeo 2011-05-26 23:28:20

+0

這不允許您傳遞結構數組(或指向結構的指針,然後使用指針數學移動到數組的下一個元素) – iheanyi 2014-08-21 20:20:57

3

你可以分配的內存塊原料,並使用安置新初始化每個struct

int number_of_structs = 10; 
my_structs = (a_struct*)new unsigned char[sizeof(a_struct) * number_of_structs]; 
    // allocate a raw chunk of memory 
a_struct* p = m_structs; 
for (int i=0; i<number_of_structs; i++) 
{ 
    new (p) a_struct(i); 
    p++; 
} 

參見:What uses are there for "placement new"?