[英]Vector of (Structs having vector)
The following piece of code as stated in Bjarne Stroustroup's C++: Programming and Principles Bjarne Stroustroup 的 C++ 中所述的以下代码:编程和原理
struct Day {
vector <double> hour { vector <double> (24,-7777)}
};
struct Month {
vector <Day> day {32};
};
This piece of code initializes 32 days, each day as a vector
of 24 hours initialized with -7777
;这段代码初始化 32 天,每天作为一个 24 小时的vector
,用-7777
初始化;
The question is why list initializer {32}
creates 32 days.问题是为什么列表初始化程序{32}
创建 32 天。 Isn't it supposed to initialize day vector
with 32 as a initial value instead of creating 32 members?难道不应该用 32 作为初始值来初始化日vector
,而不是创建 32 个成员吗?
For list initialiation ,对于 列表初始化,
Otherwise, the constructors of
T
are considered, in two phases:否则,将分两个阶段考虑T
的构造函数:All constructors that take
std::initializer_list
as the only argument, or as the first argument if the remaining arguments have default values, are examined, and matched by overload resolution against a single argument of typestd::initializer_list
所有将std::initializer_list
作为唯一参数或作为第一个参数的构造函数,如果剩余的 arguments 具有默认值,则通过重载决议对std::initializer_list
类型的单个参数进行检查和匹配If the previous stage does not produce a match, all constructors of
T
participate in overload resolution against the set of arguments that consists of the elements of the braced-init-list, with the restriction that only non-narrowing conversions are allowed.如果前一阶段没有产生匹配,则T
的所有构造函数都参与针对由括号初始化列表的元素组成的 arguments 集的重载决议,限制只允许非缩小转换。 If this stage produces an explicit constructor as the best match for a copy-list-initialization, compilation fails (note, in simple copy-initialization, explicit constructors are not considered at all).如果此阶段生成一个显式构造函数作为复制列表初始化的最佳匹配,则编译失败(注意,在简单的复制初始化中,根本不考虑显式构造函数)。
day
is of type vector <Day>
, whose constructor taking std::initializer_list
as parameter expects an std::initializer_list<Day>
, which can't be constructed from the braced-initializer {32}
. day
是vector <Day>
类型,其以std::initializer_list
作为参数的构造函数需要一个std::initializer_list<Day>
,它不能从花括号初始化器{32}
构造。 Then the constructor taking size_type
is used and construct the vector
with 32 default-inserted instances of Day
.然后使用采用size_type
的构造函数,并使用 32 个默认插入的Day
实例构造vector
。
On the other hand, if Day
could be initialized from an int
, eg has a constructor taking int
, then std::initializer_list<Day>
could be constructed from {32}
because of the implicit conversion from int
to Day
, then vector <Day> day {32};
另一方面,如果Day
可以从int
初始化,例如有一个构造函数采用int
,那么std::initializer_list<Day>
可以从{32}
构造,因为从int
到Day
的隐式转换,然后是vector <Day> day {32};
would construct the vector
with one element initialized from 32
.将使用从32
初始化的一个元素构造vector
。
The one parameter initializer list is matched to the vector constructor taking one parameter, which allocates that many elements.一个参数初始值设定项列表与采用一个参数的向量构造函数相匹配,该参数分配了那么多元素。 In this case 32.在这种情况下 32。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.