Leh*_*ehu 5 c++ static class 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
{
public:
static constexpr int sum() {return x+y+z;}
private:
static constexpr int x = 2;
static const int y = 3;
static int z;
};
int TestClass::z = 5;
int main()
{
TestClass tc;
cout << tc.sum() << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
PS我正在使用mingw32-g ++ 4.8.1
在第一种情况下,结果仅取决于函数的参数,包括this用于访问的隐式参数z。这并不妨碍它的存在constexpr——如果所有参数都是常量表达式,那么结果也是如此。
在您的示例中,它不是一个常量表达式(因为tc不是),但这并不重要,因为它没有在需要常量表达式的上下文中使用。下面的示例展示了它在常量表达式中的使用:
constexpr TestClass tc;
array<int, tc.sum()> a;
cout << a.size() << endl;
Run Code Online (Sandbox Code Playgroud)
在第二种情况下,结果还取决于静态变量,其值可能在程序期间发生变化。这确实取消了它的资格 - 即使所有参数都是常量表达式,但z不是,因此函数调用的结果永远不可能是常量表达式。