问题描述
在C ++中初始化 static
数据成员的正确方法是什么?我也对它从C ++ 98到C ++ 11到C ++ 14的变化感兴趣。
What is the right way to initialize static
data members in C++? I'm also interested in how it has changed from C++98, to C++11 to C++14.
这里是一个例子:
// bufferedOutput.h
class BufferedOutput
{
// Static member declaration.
static long bytecount;
};
// bufferedOutput.cpp
long BufferedOutput::bytecount = 50;
还有其他方法可以初始化 static
数据
Are there other ways to initialize static
data members?
推荐答案
规则始终如下:
-
整数或枚举类型的
const
静态数据成员(SDM)可以在类中使用常量表达式进行初始化。
A
const
static data member (SDM) of integral or enumeration type can be initialised in class with a constant expression.
A constexpr
SDM必须在类中使用常量表达式进行初始化。
A constexpr
SDM must be initialised in class with a constant expression.
C ++ 17在默认构造函数初始化每个成员时不再需要使用初始化程序。此外, constexpr
SDM是隐式内联变量,这使它们的声明成为定义(现已弃用外部定义)。
C++17 no longer requires an initializer when the default constructor initialises every member. Also, constexpr
SDMs are implicitly inline variables, which makes their declaration a definition (external definitions are now deprecated).
对于在两种语言中均有效的代码,C ++ 03和C ++ 11 +之间没有任何实质性改变。
Nothing has substantially changed between C++03 and C++11+ for code that is valid in both languages.
请注意,对于非内联的SDM,无论是否提供了初始化程序,类内声明都不是一种定义,并且必须对它们进行定义。
Note that for SDMs that are not inline, the in-class declaration is not a definition—regardless of whether an initializer is provided—and they must be defined if they are odr-used.
从C ++ 17开始,我们可以使您的SDM内联,从而使其类内声明成为定义:
As of C++17, we can make your SDM inline, which makes its in-class declaration a definition:
class BufferedOutput
{
static inline long bytecount = 50;
};
这篇关于在C ++(98、11和14)中初始化静态数据成员的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!