3 个级别的初始化列表

Man*_*kie 3 c++ initialization class stdvector c++11

如何正确且轻松地初始化class包含std::vector某个其他类的 a 的实例,该类本身包含一些数据。

我知道用文字来解释它真的很难,所以我会写一段不起作用的代码,但它抓住了我的意图。

#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;
}
Run Code Online (Sandbox Code Playgroud)

此代码不起作用。Clang 返回错误 -

excess elements in struct initializer
Run Code Online (Sandbox Code Playgroud)

我不明白为什么它给我这个错误。

我想我可以初始化

  • std::vectorTriangle小号
  • 然后是Points的数组,
  • 然后是float每个Point对象中的两个s 。

我将如何Geometry使用一些值正确初始化类的实例而不使用初始化方括号编写太多代码

如果您有其他选择,那么我愿意考虑它们。

cig*_*ien 6

您需要 2 对额外的括号才能工作:

Geometry instance
{{
  {{{0,0}, {6, 0}, {3, 3}}},
  {{{5,2}, {6, 6}, {7, 3}}}
}};
Run Code Online (Sandbox Code Playgroud)

这是一个演示

所有大括号的解释:

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}}}
}};
Run Code Online (Sandbox Code Playgroud)

虽然我喜欢使用大括号初始化列表,但当你嵌套这么深时,明确地拼出类型可能更具可读性。