c++ - 在类中初始化静态结构 tm

标签 c++ class static struct ctime

我想将 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/

相关文章:

c - 错误 C4700 : uninitialized local variable "" used

c++ - 如何在 GNU Radio 中实现消息传递?

c++ - 基类中奇怪的重复模板模式和静态

c++ - sprintf 缓冲区问题,错误分配给 char 数组

html - 如何将多个类分配给 HTML 容器?

python - 我应该为 Python 中的类作用域变量使用 "global"还是 "self."?

php - 最终的静态类方法是否可能?

c - 静态变量有什么错误吗?

c++ - 小写 null 在 C++ 中有效吗?

c++ - 如果两个线程同时访问同一个 bool 变量会发生什么?