Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: dynamically allocating a member array of structs using non-default constructor

If I have:

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() {...}
};  

I can do:

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

But I cannot do:

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

Is there any correct syntax to get this to work? Or an easy work around?

like image 927
Matt Munson Avatar asked May 26 '11 22:05

Matt Munson


1 Answers

If using the STL is an option, you could use std::vector instead of a dynamic array.

I think that this will work:

std::vector<a_struct> my_structs;

my_structs.assign(10, 1);

If not, this should:

my_structs.assign(10, a_struct(1));
like image 75
CariElf Avatar answered Oct 17 '22 19:10

CariElf