有没有办法通过包含基本结构成员变量来使用大括号初始化子结构。我正在尝试以下操作,但无法编译(使用 VS 和 C++ 20)。 我不想创建构造函数,而是想使用单行构造。
struct Base
{
int n;
};
struct Derived : Base
{
std::string s;
}
static const Derived d1{ .s = "Hi", { .n = 1 } }; //fails to compile
static const Derived d2{ 1, { "Hi" } }; //fails to compile
static const Derived d3{ 1, "Hi" }; //fails to compile
static const Derived d4(1, "Hi"); //fails to compile
编辑:
d4, d3
实际上编译得很好。
这对我有用,https://godbolt.org/z/oYWYr5Gc7:
#include <string>
struct Base {
int n;
};
struct Derived : Base {
std::string s;
};
// Designated-initializers must be in the order of the member declarations.
// Base data members precede Derived data members.
static const Derived d1 = {{.n = 1}, .s = "Hi"};
static const Derived d2{1, {"Hi"}};
static const Derived d3{ 1, "Hi" };
// It does not work because Derived does not have the constructor.
// static const Derived d4(1, "Hi");