Why I am getting this error: constexpr' is not valid here

Why I am getting this error: constexpr' is not valid here

我有这个代码:

class myClass
{
        constexpr int x = 4;
};

2015 年 visual studio,我收到此错误:

'constexpr' is not valid here

为什么会出现这个错误?我想要一个常量静态变量,我可以在头文件中初始化它。

下一步我想把我的class改成一个模板,但是这个常量与类的类型无关。

static 数据成员不能声明为constexpr。使用

class myClass
{
    static constexpr int x = 4;
};

相反。

I want a const static variable that I can initlaize it on header file

如果您主要关心的是可共享给所有模板类型实例的常量值,那么您可以更改为以下内容:

class myClass
{
    static const int x = 4;
};

如果您担心内存space(尽管它在所有实例之间共享),您可以只使用编译预处理解决方案(即#Define X 4)