一个基本的问题,但我很难找到一个明确的答案。
除了方法中的赋值之外,初始化程序列表是在 C++ 中初始化类字段的唯一方法吗?
如果我使用了错误的术语,这就是我的意思:
class Test
{
public:
Test(): MyField(47) { } // acceptable
int MyField;
};
class Test
{
public:
int MyField = 47; // invalid: only static const integral data members allowed
};
编辑:特别是,有没有一种用结构初始化器初始化结构字段的好方法?例如:
struct MyStruct { int Number, const char* Text };
MyStruct struct1 = {}; // acceptable: zeroed
MyStruct struct2 = { 47, "Blah" } // acceptable
class MyClass
{
MyStruct struct3 = ??? // not acceptable
};