向量(具有向量的结构)

Vector of (Structs having vector)

Bjarne Stroustroup's C++: Programming and Principles 中所述的以下代码

struct Day {
    vector <double> hour { vector <double> (24,-7777)}
};
struct Month {
    vector <Day> day {32};
};

这段代码初始化了 32 天,每一天都是用 -7777 初始化的 24 小时的 vector

问题是为什么列表初始值设定项 {32} 创建 32 天。 不是应该创建dayvector初始值32而不是创建32个成员吗?

单参数初始值设定项列表匹配向量 constructor 采用一个参数,它分配那么多元素。在这种情况下 32.

对于list initialiation,

Otherwise, the constructors of T are considered, in two phases:

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 type 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. 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 是类型 vector <Day>,其 constructor taking std::initializer_list as parameter expects an std::initializer_list<Day>, which can't be constructed from the braced-initializer {32}. Then the constructor taking size_type 被使用并构造 vector 与 32 个默认插入的 Day 实例。

另一方面,如果 Day 可以从 int 初始化,例如有一个采用 int 的构造函数,那么 std::initializer_list<Day> 可以从 {32} 构造,因为从 intDay 的隐式转换,那么 vector <Day> day {32}; 会使用从 32 初始化的一个元素构造 vector

LIVE