类字段如何初始化?
这是一个基本问题,但我很难找到明确的答案。
除了方法中的赋值之外,初始化器是否列出了 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
};
A bit of a basic question, but I'm having difficulty tracking down a definitive answer.
Are initializer lists the only way to initialize class fields in C++, apart from assignment in methods?
In case I'm using the wrong terminology, here's what I mean:
class Test
{
public:
Test(): MyField(47) { } // acceptable
int MyField;
};
class Test
{
public:
int MyField = 47; // invalid: only static const integral data members allowed
};
EDIT: in particular, is there a nice way to initialize a struct field with a struct initializer? For example:
struct MyStruct { int Number, const char* Text };
MyStruct struct1 = {}; // acceptable: zeroed
MyStruct struct2 = { 47, "Blah" } // acceptable
class MyClass
{
MyStruct struct3 = ??? // not acceptable
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 C++x0 中,第二种方法也应该有效。
就您的编译器而言:是的。
In C++x0 the second way should work also.
In your case with your compiler: Yes.
静态成员可以以不同的方式初始化:
我不知道你是否称其为“好”,但你可以相当干净地初始化结构成员,如下所示:
Static members can be initialised differently:
I don't know if you call this 'nice', but you can initialise struct members fairly cleanly like so:
只是提一下,在某些情况下,您别无选择,只能使用初始值设定项列表在构造时设置成员的值:
Just to mention that in some cases, you have no choice but to use initializer lists to set a member's value on construction:
推荐和首选的方法是初始化构造函数中的所有字段,就像第一个示例一样。这对于结构也有效。请参阅此处:在类中初始化 static struct tm
The recommended and preferred way is to initialize all fields in the constructor, exactly like in your first example. This is valid also for structs. See here: Initializing static struct tm in a class