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

后端 未结 4 1028
暖寄归人
暖寄归人 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:22

    You can't do it directly on any particular parameterized constructor. However you can do,

    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
    

    When you're going to de-allocate the memory,

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

    I suggest using a std::vector container instead of going through this process.

提交回复
热议问题