小编Leh*_*ehu的帖子

当非const成员可以在constexpr成员函数中使用?

我遇到了一个我不明白的情况.有人会这么好解释为什么第一个代码正确编译而第二个代码出错:

错误:'TestClass :: z'的值在常量表达式中不可用
static constexpr int sum(){return x + y + z;}
----------------- ----------------------------------- ^
注意:'int TestClass :: z'不是const static int Z者除外;"

工作代码:

#include <iostream>

using namespace std;

class TestClass
{
    public:
        constexpr int sum() {return x+y+z;}

    private:
        static constexpr int x = 2;
        static const int y = 3;
        int z = 5;

};

int main()
{
    TestClass tc;
    cout << tc.sum() << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试制作TestClass::sum()静态时,我得到了上述错误:

#include <iostream>

using namespace std;

class TestClass
{ …
Run Code Online (Sandbox Code Playgroud)

c++ static class constexpr

5
推荐指数
1
解决办法
853
查看次数

标签 统计

c++ ×1

class ×1

constexpr ×1

static ×1