4

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.

4

4 回答 4

2

您可以像这样在声明时执行它们

_creationDate = {0}; // set everything to 0's

或者像这样

_creationDate = { StructElement1, StructElement2, ..., StructElement n);

_creationDate = { 0, false, 44.2);

或者在您的构造函数中,只需调用结构中的每个元素并进行初始化,例如...

_creationData.thing1 = 0;
_creationData.thing2 = false;
_creationData.thing3 = 66.3;
于 2010-10-31T23:23:38.143 回答
1

我认为你只能在定义它时初始化这样的结构:

struct tm a = {0}; // works ok
struct tm b;
b = {0};           // error

一种选择是使用“默认”值

class a
{
    a() : t() {}
    struct tm t;
};

memset在构造函数中:

struct tm creationDate;
memset((void*)&creationDate, 0, sizeof(struct tm));
于 2010-10-31T23:31:55.287 回答
1

在 C++03 中唯一可行的方法:

class foo
{
    tm _creationDate;
    public:
    foo()
    {
        tm tmp_tm = {0};
        _creationDate = tmp_tm;
    }
};

请注意,这将_creationDate使用 的副本进行初始化tmp_tm,从而调用(很可能是自动生成的)复制构造函数。因此,对于大型结构,您应该坚持使用实用功能,因为这不需要复制整个结构。

顺便说一句,以下划线开头的名称(在全局范围内)是为标准库实现保留的。以下划线后跟大写字母开头的名称在任何地方都保留。从技术上讲,这里的名称_creationDate很好,因为它不在全局范围内,但我仍然建议避免在名称中使用前导下划线。

于 2010-11-01T01:03:48.073 回答
1

http://www.cprogramming.com/tutorial/initialization-lists-c++.html

class C {
    struct tm  _creationDate;
    struct tm  _expirationDate;
    struct tm  _lockDate;
    C() : _creationDate(), ... {}
于 2010-10-31T23:20:29.383 回答