C++ 初始化静态常量结构变量

标签 c++ static struct initialization constants

我正在尝试向我的类添加一个静态常量变量,它是一个结构的实例。因为它是静态的,所以我必须在类声明中对其进行初始化。尝试这段代码

class Game {
    public:
        static const struct timespec UPDATE_TIMEOUT = { 10 , 10 };

    ...
};

出现此错误:

error: a brace-enclosed initializer is not allowed here before '{' token

error: invalid in-class initialization of static data member of non-integral type 'const timespec'

如何初始化它?谢谢!

最佳答案

在源文件内的类外的单独定义中初始化它:

// Header file
class Game {
    public:
        // Declaration:
        static const struct timespec UPDATE_TIMEOUT;
    ...
};

// Source file
const struct timespec Game::UPDATE_TIMEOUT = { 10 , 10 };  // Definition

如果您将定义包含在一个头文件中,并且该头文件包含在多个源文件中,您可能会收到有关多重定义符号的链接器错误。

关于C++ 初始化静态常量结构变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12079537/

相关文章:

c++ - 使用引用生成 IBM Rhapsody 访问器

c++ - 在 Windows 上为 glut 3.7 构建静态库

c - 结构指针设置值

C struct 语法的说明

php - 将 PHP 页面转换为静态 HTML 页面的最简单方法

c - 结构体指针和内存位置

c# - 从 C# 调用非托管 .dll 的性能

c++ - 从 RAM 驱动器构建真的会提高速度吗?

c++ - C2065 'cout' : undeclared identifier

java - 在 Mac OS X 10.6 上从 x86_64 .a 文件创建 jnilib