Initializing tm static structure in class

I would like to use tm struct as a static variable in the class. He spent the whole day reading and trying, but he still can’t work :( I would understand if someone could indicate what I was doing wrong.

In my class under Public, I declared it as:

static struct tm *dataTime; 

In main.cpp, I tried to define and initialize it with the system time for checking (actual time for input at runtime)

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

but it looks like I cannot use the external time () functions.

main.cpp: 28: error: constructor, destructor, or type conversion to 'expected (token)

How to initialize values ​​in a static tm class?

+3
c ++ struct static class ctime
source share
6 answers

You can wrap this in a function:

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

To avoid possible binding problems, make a static function or place it in an unnamed namespace.

+7
source share
 struct tm get_current_localtime() { time_t now = time(0); return *localtime(&now); } struct tm Indice::dataTime = get_current_localtime(); 
+4
source share

You cannot call functions arbitrarily outside functions. Either perform initialization in your main() function, or create a wrapper class around the tm structure with a constructor that performs the initialization.

+2
source share

Wrap it all in a function and use to initialize your static member:

 tm gettime() { time_t rawTime; time ( &rawTime ); return localtime(&rawTime); } tm Indice::dataTime = gettime(); 

And you don't need (and therefore shouldnt) a prefix for using a structure with struct in C ++: tm enough, you don't need struct tm .

+2
source share

Also note that your struct tm is a pointer to a tm structure. Returning from localtime is a one-point pointer, the contents of which will change when you or anyone else calls the local time again.

+1
source share

Add this:

 namespace { class Initializer { public: Initializer() { time_t rawtime; time(&rawtime); YourClass::dataTime = localtime(&rawtime); } }; static Initializer myinit(); } 

When the file object is initialized at run time, the Initializer () constructor is called, which then sets the "global" dataTime variable as you want. Note that the anonymous namespace design helps prevent potential collisions for the Initializer and myinit names.

0
source share

All Articles