在类中初始化静态struct tm [英] Initializing static struct tm in a class
问题描述
我想使用tm结构作为类中的静态变量。花了一整天的时间阅读和尝试,但它仍然不能工作:(如果有人可以指出我做错了什么感谢。
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;
在main.cpp中,我试图定义和初始化它与系统时间临时测试(在运行时输入的实际时间)
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);
但似乎我不能使用time()外部函数。
but seems like i can't use time() outside functions.
main.cpp:28:error:expected
构造函数,析构函数或类型
$ b
main.cpp:28: error: expected constructor, destructor, or type conversion before ‘(’ token
如何初始化类的静态tm中的值?
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();
为避免可能的链接问题,请将函数设为static或将其放入未命名的命名空间。
To avoid possible linking problems, make the function static or put it in an unnamed namespace.
这篇关于在类中初始化静态struct tm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!