我们可以为带有参数化构造函数的结构初始化数组吗?

时间:2018-09-28 20:50:50

标签: c++ constructor

我们可以为具有默认构造函数的结构初始化数组,但是可以使用参数化构造函数来做到这一点吗?

struct class{
   int room;
   int floor;
   class(){
    room=0;
    floor=0;
  }
};

int main(){
   class c1[5];
}

以上代码可以正常工作。但是,当有参数化的构造函数时该怎么办?

struct class{
  int room;
  int floor;
  class(int r,int f){
    room=r;
    floor=f;
  }
};

1 个答案:

答案 0 :(得分:1)

您可以使用列表初始化:

struct test {
  test(int,int);
};

test c1[] = {
    {1, 2},
    {3, 4},
    {5, 6},
};