我想将 tm 结构用作类中的静态变量。花了一整天的时间阅读和尝试,但仍然无法正常工作:(如果有人能指出我做错了什么,我将不胜感激
在我的类里面,在 Public 下,我将其声明为:
static struct tm *dataTime;
在main.cpp中,我尝试用系统时间来定义和初始化它,暂时测试一下(实际时间要在运行时输入)
time_t rawTime;
time ( &rawTime );
tm Indice::dataTime = localtime(&rawTime);
但似乎我不能在函数外使用 time()。
main.cpp:28: error: expected constructor, destructor, or type conversion before ‘(’ token
如何在类的静态 tm 中初始化值?
最佳答案
您可以将上面的内容包装在一个函数中:
tm initTm() {
time_t rawTime;
::time(&rawTime);
return *::localtime(&rawTime);
}
tm Indice::dataTime = initTm();
为避免可能的链接问题,将函数设为静态或将其放在未命名的命名空间中。
关于c++ - 在类中初始化静态结构 tm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2105077/