有点基本的问题,但我很难找到明确的答案。
除了方法中的赋值之外,初始化列表是唯一在 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
};
最佳答案
在 C++x0 中,第二种方式也应该有效。
Are initializer lists the only way to initialize class fields in C++?
对于您的编译器而言:是的。
关于c++ - 如何初始化类字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3264597/