你就快到了。
MyStruct x = { 1, "string" };
被称为
复制列表初始化
MyStruct
带括号的初始化列表
你的问题是你的构造函数需要一个
char*
虽然
"string"
const char[N]
它可以衰变为
const char*
.所以让事情改变
struct MyStruct {
int field1;
const char* field2;
MyStruct(int a, const char* b): field2(b) {
field1 = a;
}
MyStruct(int a): MyStruct(a, nullptr) {}
~MyStruct() {}
};
然后
MyStruct x = { 1, "string" };
field2
成为一名
std::string
struct MyStruct {
int field1;
std::string field2;
MyStruct(int a, const std::string& b): field1(a), field2(b) {}
MyStruct(int a): MyStruct(a, "") {}
~MyStruct() {}
};