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

后端 未结 4 1031
暖寄归人
暖寄归人 2020-12-10 15:33

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;         


        
4条回答
  •  暖寄归人
    2020-12-10 16:09

    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 my_structs;
    
    my_structs.assign(10, 1);
    

    If not, this should:

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

提交回复
热议问题