【问题标题】:Can we initialize an array for a structure with a parametrized constructor? [duplicate]我们可以使用参数化构造函数为结构初始化数组吗? [复制]
【发布时间】:2018-09-28 20:50:49
【问题描述】:

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

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

【问题讨论】:

  • 类名不能有关键字。

标签: c++ constructor


【解决方案1】:

可以使用列表初始化:

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

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

【讨论】:

  • 我可以将其设为用户输入数组吗?
猜你喜欢
  • 1970-01-01
  • 2015-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-28
  • 1970-01-01
  • 2020-12-29
相关资源
最近更新 更多