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

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

    You could use an array of pointers to pointers. Then you can create the array that will hold pointers to a_struct(), so you can decide later which constructor to use:

    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);
        }
    }; 
    

提交回复
热议问题