Using the const int variable in a switch statement

I am using gcc with the flag -std = C ++ 11. In my class definition, I have the following:

private: const int January = 1, February = 2, March = 3, ... 

In my implementation, I have a switch statement.

 switch (currentMonth) { case January: returnString = "January"; break; case February: returnString = "February"; break; case March: returnString = "March"; break; ... 

It seems that it should work as the months are constant; however gcc gives me

 calendar.cpp:116:12: error: 'this' is not a constant expression 

in each case the switch statement. Why is this wrong?

+7
source share
2 answers

Non-static members of a class are not constant expressions. Try the following:

 static constexpr int January = 1; 
+11
source

try the following:

 enum { January = 1, February = 2 ... }; 
+2
source

All Articles