Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing static struct tm in a class

I would like to use the tm struct as a static variable in a class. Spent a whole day reading and trying but it still can't work :( Would appreciate if someone could point out what I was doing wrong

In my class, under Public, i have declared it as:

static struct tm *dataTime;

In the main.cpp, I have tried to define and initialize it with system time temporarily to test out (actual time to be entered at runtime)

time_t rawTime;
time ( &rawTime );
tm Indice::dataTime = localtime(&rawTime);

but seems like i can't use time() outside functions.

main.cpp:28: error: expected constructor, destructor, or type conversion before ‘(’ token

How do I initialize values in a static tm of a class?

like image 344
eruina Avatar asked Dec 04 '22 13:12

eruina


2 Answers

You can wrap the above in a function:

tm initTm() {
    time_t rawTime;
    ::time(&rawTime);
    return *::localtime(&rawTime);
}

tm Indice::dataTime = initTm();

To avoid possible linking problems, make the function static or put it in an unnamed namespace.

like image 115
Georg Fritzsche Avatar answered Dec 20 '22 23:12

Georg Fritzsche


struct tm get_current_localtime() {
    time_t now = time(0);
    return *localtime(&now);
}

struct tm Indice::dataTime = get_current_localtime();
like image 23
Chris Jester-Young Avatar answered Dec 21 '22 00:12

Chris Jester-Young