难道一个类型要求,以宣布它的一个阵列默认构造函数? [英] Does a type require a default constructor in order to declare an array of it?
问题描述
我注意到,当你声明一个数组,必须所需的默认构造函数。是对的吗?
有没有例外?
I noticed that when you declare an array, the default constructor must be needed. Is that right? Is there any exception?
例如,
struct Foo{
Foo(int i ) {}
};
int main () {
Foo f[5];
return 0;
}
在code以上不能编译。
The code above does not compile.
推荐答案
其他答案都是正确的,但出于完整性:您还可以使用数组初始化语法:
Other answers are all right but, for completeness: You could also use the array initialization syntax:
Foo f[5] = {1,2,3,4,5};
这工作,如果Foo的构造函数不明确。如果是,你必须是明确的....:
This works if Foo's ctor is not explicit. If it was, you'd have to be.... explicit:
Foo f[5] = {Foo(1), Foo(2), Foo(3), Foo(4), Foo(5)};
注意 1 :有两种情况之间的差异,可能不是很明显,因此值得关注:第一,数组元素是直接从构造在 INT
■在初始化列表,通过调用美孚(INT)
构造函数。第二,初始化列表是由富
第构建与明确美孚(INT)
构造函数,和数组元素的复制从初始化列表中的元素构造的。从而为富副本构造函数,需要在后一种情况下
Note1: There is a difference between the two cases that may not be obvious and is thus worth noting: In the first, the array elements are directly constructed from the int
s in the initialization list, by invoking the Foo(int)
ctor. In the second, the initialization list is made of Foo
s constructed with the explicit Foo(int)
ctor, and the array elements are copy constructed from the elements in the initialization list. A copy ctor for Foo is thus required in the latter case.
[1]由于MSalters的评论。
[1] Thanks to MSalters for the comment.
这篇关于难道一个类型要求,以宣布它的一个阵列默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!