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?
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.
struct tm get_current_localtime() {
time_t now = time(0);
return *localtime(&now);
}
struct tm Indice::dataTime = get_current_localtime();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With