C++ 初始化静态 const 结构变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12079537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ Initializing static const structure variable
提问by Kolyunya
I'm trying to add a static constant variable to my class, which is an instance of a structure. Since it's static, I mustinitialize it in class declaration. Trying this code
我正在尝试向我的类添加一个静态常量变量,它是一个结构的实例。由于它是静态的,我必须在类声明中对其进行初始化。试试这个代码
class Game {
public:
static const struct timespec UPDATE_TIMEOUT = { 10 , 10 };
...
};
Getting this error:
收到此错误:
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'
错误:此处不允许在“{”标记之前使用大括号括起来的初始值设定项
错误:非整数类型“const timespec”的静态数据成员的类内初始化无效
How do I initialize it? Thanks!
我如何初始化它?谢谢!
回答by Adam Rosenfield
Initialize it in a separate definition outside the class, inside a source file:
在类外的源文件内的单独定义中初始化它:
// Header file
class Game {
public:
// Declaration:
static const struct timespec UPDATE_TIMEOUT;
...
};
// Source file
const struct timespec Game::UPDATE_TIMEOUT = { 10 , 10 }; // Definition
If you include the definition in a header file, you'll likely get linker errors about multiply defined symbols if that header is included in more than one source file.
如果将定义包含在头文件中,并且该头文件包含在多个源文件中,则您可能会收到有关多重定义符号的链接器错误。
回答by David Nogueira
Declare the variable as a static variable inside a function and make that function return the reference to the variable.
在函数内将该变量声明为静态变量,并使该函数返回对该变量的引用。