在类中初始化静态struct tm

eru*_*ina 4 c++ static struct class ctime

我想在类中使用tm结构作为静态变量.花了一整天阅读和尝试但它仍然无法工作:(如果有人能指出我做错了什么会很感激

在我的班级中,在Public下,我已将其声明为:

static struct tm *dataTime;
Run Code Online (Sandbox Code Playgroud)

在main.cpp中,我试图用系统时间临时定义和初始化它来测试(在运行时输入的实际时间)

time_t rawTime;
time ( &rawTime );
tm Indice::dataTime = localtime(&rawTime);
Run Code Online (Sandbox Code Playgroud)

但似乎我不能使用time()外部函数.

main.cpp:28:错误:在'('标记之前)期望的构造函数,析构函数或类型转换

如何初始化类的静态tm中的值?

Geo*_*che 7

你可以在函数中包含上面的内容:

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

tm Indice::dataTime = initTm();
Run Code Online (Sandbox Code Playgroud)

要避免可能的链接问题,请将该函数设置为static或将其放在未命名的命名空间中.

  • +1对于未命名的命名空间.(咳嗽,不是匿名,咳嗽) (2认同)