如何在C 类的初始化器列表中使用未命名结构初始化成员结构

How to initialize member-struct with unnamed structure in initializer list of C++ class?

本文关键字:初始化 结构 未命名 成员 列表      更新时间:2023-10-16

i具有内部未命名结构的结构。我想初始化整个结构,并且它的成员结构在类初始化器列表中。

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;
};

如果我正确理解您,请在Bar的初始化器列表中初始化包含未命名struct struct Foo

#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;
}

如果我正确理解,您想对完整结构的静态初始化,包括内在 nmind nameed struct。

您是否尝试过:

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