基础 C++:如何初始化类的结构成员?
我查遍了所有地方,但还没有找到这个问题的答案。
我有一个带有这些受保护成员的 C++ 类:
struct tm _creationDate;
struct tm _expirationDate;
struct tm _lockDate;
我想在实例化时初始化它们。如果我将其放入构造函数中:
_creationDate = {0};
_expirationDate = {0};
_lockDate = {0};
编译器会抱怨:“在 '{' 标记之前需要主表达式”,
我也找不到在构造函数顶部的成员初始化列表中执行此操作的方法。如何做到这一点?谢谢!
后续行动: 谢谢你们的回复,伙计们。你不能在声明中这样做;这是不允许的。因此,唯一的方法似乎是 memset 或单独设置成员。我最终编写了一个实用函数来做到这一点。
I've looked all over the place, but haven't found an answer to this.
I have a C++ class with these protected members:
struct tm _creationDate;
struct tm _expirationDate;
struct tm _lockDate;
I want to initialize them at instantiation time. If I put this in the constructor:
_creationDate = {0};
_expirationDate = {0};
_lockDate = {0};
the compiler complains: "expected primary-expression before '{' token"
I also can't find a way to do it in a member-initializer list at the top of the constructor. How does one do this? Thanks!
FOLLOW-UP:
Thanks for the replies, guys. You can't do it at the declaration; that's not allowed. So the only way appears to be memset or setting the members individually. I ended up writing a utility function to do just that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在像这样
或这样
的
声明中执行它们,或者在构造函数中只需调用结构中的每个元素并初始化,例如...
You can either do them at declaration like this
or like this
such as
Or in your constructor just call out each element in the structure and initialize such as...
http://www.cprogramming.com/tutorial/initialization-lists-c++.html
http://www.cprogramming.com/tutorial/initialization-lists-c++.html
我认为您只能在定义结构时初始化这样的结构:
一种选择是在构造函数中使用“默认”值
或
memset
:I think you can only initialize structure like that when you define it:
One option is either to use "default" values
Or
memset
in constructor:C++03 中唯一可能的方法:
请注意,这将使用
tmp_tm
的副本初始化_creationDate
,从而调用(最有可能自动生成的)复制构造函数。因此,对于大型结构,您应该坚持使用实用函数,因为这不需要复制整个结构。顺便说一下,以下划线开头的名称(在全局范围内)是为标准库实现保留的。以下划线开头,后跟大写字母的名称在任何地方都被保留。从技术上讲,这里的名称
_creationDate
很好,因为这不在全局范围内,但我仍然建议避免在名称中使用前导下划线。Only way possible in C++03:
Note that this will initialize
_creationDate
with a copy oftmp_tm
, thus invoking the (most likely autogenerated) copy-constructor. So for large structs, you should rather stick with your utility function, since that will not require copying the whole struct.And by the way, names starting with an underscore (at global scope) are reserved for the standard library implementation. Names starting with an underscore followed by an uppercase letter are reserved everywhere. Technically the name
_creationDate
here is fine, since this is not at global scope, but I would still recommend to avoid using a leading underscore for names.