如何在C ++类的初始化列表中初始化具有未命名结构的member-struct?

时间:2017-09-01 07:18:11

标签: c++ struct constructor initialization initializer-list

我的结构里面有一个未命名的结构。我想初始化整个结构及其在类初始化列表中的成员结构。

struct Foo {
  int z;
  struct {
    double upper;
    double lower;
  } x, y;
};

class Bar {
  Bar();

  Foo foo;
};

可以这样做吗?

此结构也可以初始化"旧时尚"提供没有统一初始化语法的构造函数的方法?

struct Foo {
    Foo() : z(2), x(/*?*/), y(/*?*/) {}
    Foo() : z(2), x.lower(2) {} // doesn't compile
    int z;
    struct {
      double upper;
      double lower;
    } x, y;
};

2 个答案:

答案 0 :(得分:4)

如果我理解正确,您需要在struct Foo的初始值设定项列表中初始化Bar,其中包含unnamed struct

#include <iostream>

struct Foo {
  int z;
  struct {
    double upper;
    double lower;
  } x, y;
};

class Bar {
public:
  Bar();

  Foo foo;
};

Bar::Bar()
: foo { 1, { 2.2, 3.3}, {4.4, 5.5} }
{

}

int main()
{
    Bar b;

    std::cout << b.foo.z << std::endl;
    std::cout << b.foo.x.upper << std::endl;
    std::cout << b.foo.y.lower << std::endl;
}

答案 1 :(得分:0)

如果我理解正确,您希望对完整结构进行静态初始化,包括内部未命名结构。

你有没有尝试过:

Foo foo { 1,            // z
        {1.1, 2.2},     // x
        {3.3, 4.4}};    // y