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

Can we initialize an array for a structure with a parametrized constructor?

本文关键字:结构 数组 初始化 构造函数 参数 我们      更新时间:2023-10-16

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

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

您可以使用列表初始化:

struct test {
test(int,int);
};
test c1[] = {
{1, 2},
{3, 4},
{5, 6},
};