I came across a situation that I do not understand. Someone will explain so well why the first code compiles correctly and the second gives an error:
error: the value "TestClass :: z" cannot be used in the constant expression
static constexpr int sum () {return x + y + z;}
-------------------- ------------------------------ - ^
note: 'int TestClass :: z' is not a constant static int z; "
Work code:
#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;
}
But when I try to make static TestClass::sum()static, I get the above error:
#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;
}
PS I am using mingw32-g ++ 4.8.1
source
share