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

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 に答える
1

構造を定義するときにのみ、そのような構造を初期化できると思います。

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

1 つのオプションは、「デフォルト」値を使用することです。

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

またはmemsetコンストラクターで:

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