3 个级别的初始化列表
Initializer-list on 3 levels
如何正确且轻松地初始化 class
的实例,其中包含其他 class 的 std::vector
,而后者本身包含一些数据。
我明白用文字很难解释,所以我会写一段代码,虽然不行,但它抓住了我的意图。
#include <vector>
struct Point
{
float x, y;
};
struct Triangle
{
Point points[3];
};
struct Geometry
{
std::vector<Triangle> triangles;
};
int main()
{
Geometry instance
{
{{0,0}, {6, 0}, {3, 3}},
{{5,2}, {6, 6}, {7, 3}}
};
return 0;
}
此代码无效。 Clang returns 一个错误 -
excess elements in struct initializer
我不明白为什么会出现这个错误。
我想我可以初始化
Triangle
的std::vector
,
- 然后
Point
的数组,
- 然后每个
Point
对象中的两个 float
。
我将如何使用一些值 正确初始化 Geometry
class 的实例,而无需使用初始化程序括号 编写太多代码?
如果您有其他选择,我愿意考虑。
您可以提及 triangles
的类型并提供一组额外的括号,then it should work
Geometry instance{
std::vector<Triangle> // explicitly mentioning the type
{
{ { {0,0}, {6, 0}, {3, 3}} },
{ { {0,0}, {6, 0}, {3, 3}} }
}
};
您需要 2 对额外的牙套才能工作:
Geometry instance
{{
{{{0,0}, {6, 0}, {3, 3}}},
{{{5,2}, {6, 6}, {7, 3}}}
}};
这是一个demo。
所有括号的解释:
Geometry instance
{ // for the Geometry object - instance
{ // for the vector member - triangles
{ // for the individual Triangle objects
{ // for the Point array - points[3]
{0,0}, {6, 0}, {3, 3}}}, // for the individual Points
{{{5,2}, {6, 6}, {7, 3}}}
}};
虽然我喜欢使用 brace-init 列表,但当嵌套这么深时,明确说明类型可能更具可读性。
如何正确且轻松地初始化 class
的实例,其中包含其他 class 的 std::vector
,而后者本身包含一些数据。
我明白用文字很难解释,所以我会写一段代码,虽然不行,但它抓住了我的意图。
#include <vector>
struct Point
{
float x, y;
};
struct Triangle
{
Point points[3];
};
struct Geometry
{
std::vector<Triangle> triangles;
};
int main()
{
Geometry instance
{
{{0,0}, {6, 0}, {3, 3}},
{{5,2}, {6, 6}, {7, 3}}
};
return 0;
}
此代码无效。 Clang returns 一个错误 -
excess elements in struct initializer
我不明白为什么会出现这个错误。
我想我可以初始化
Triangle
的std::vector
,- 然后
Point
的数组, - 然后每个
Point
对象中的两个float
。
我将如何使用一些值 正确初始化 Geometry
class 的实例,而无需使用初始化程序括号 编写太多代码?
如果您有其他选择,我愿意考虑。
您可以提及 triangles
的类型并提供一组额外的括号,then it should work
Geometry instance{
std::vector<Triangle> // explicitly mentioning the type
{
{ { {0,0}, {6, 0}, {3, 3}} },
{ { {0,0}, {6, 0}, {3, 3}} }
}
};
您需要 2 对额外的牙套才能工作:
Geometry instance
{{
{{{0,0}, {6, 0}, {3, 3}}},
{{{5,2}, {6, 6}, {7, 3}}}
}};
这是一个demo。
所有括号的解释:
Geometry instance
{ // for the Geometry object - instance
{ // for the vector member - triangles
{ // for the individual Triangle objects
{ // for the Point array - points[3]
{0,0}, {6, 0}, {3, 3}}}, // for the individual Points
{{{5,2}, {6, 6}, {7, 3}}}
}};
虽然我喜欢使用 brace-init 列表,但当嵌套这么深时,明确说明类型可能更具可读性。