C++:使用非默认构造函数动态分配结构的成员数组

Mat*_*son 8 c++ arrays constructor struct memory-management

如果我有:

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() {...}
};  
Run Code Online (Sandbox Code Playgroud)

我可以:

a_class() {my_structs = new a_struct(1)}
//or  
a_class() {my_structs = new a_struct [10]}
Run Code Online (Sandbox Code Playgroud)

但我不能这样做:

a_class() {my_structs = new a_struct(1) [10]}
//or
a_class() {my_structs = new a_struct() [10]}
Run Code Online (Sandbox Code Playgroud)

有没有正确的语法来使这个工作?或者轻松解决?

小智 5

如果使用STL是一个选项,则可以使用std :: vector而不是动态数组.

我认为这会奏效:

std::vector<a_struct> my_structs;

my_structs.assign(10, 1);
Run Code Online (Sandbox Code Playgroud)

如果没有,这应该:

my_structs.assign(10, a_struct(1));
Run Code Online (Sandbox Code Playgroud)

  • 或者只是`std :: vector <a_struct> my_structs(10,1);` (2认同)