先放测试后得到的结论,如下表所示。
| 静态成员变量类型 | 是否可以类内初始化 |
|---|---|
| static int | 不可以 |
| static const int | 可以 |
| static const float | 不可以 |
| static constexpr int | 必须 |
总的来说,只有在以下两种情况下,静态成员变量才可以在类内初始化。
- 使用const修饰的静态整型变量:比如static const int | char | long等。
- 使用constexpr修饰的所有静态变量:比如static constexpr int | float | double等。
注:第二种类型的变量必须在类内进行初始化。 此外,非静态成员变量不能用constexpr修饰。
测试代码如下:
class ConstTest {
public:
static int a = 1; // true
static float b = 0.1; // false
static const float c = 0.1; // false
static constexpr float d; // false
static const int e = 1; // true
static constexpr int f = 1; // true
static constexpr float g = 0.1; // true
static const int h; // true
};
const int ConstTest::h = 1;



