且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在switch语句中使用const int变量

更新时间:2023-01-19 18:33:59

非静态类成员不是常量表达式。尝试以下操作:

 静态constexpr int = 1; 


I am using gcc with the -std=c++11 flag. 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;
   ...

This seems like it should work since the months are constant; however, gcc gives me

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

on each case of the switch statement..Why is this wrong?

Non-static class members aren't constant expressions. Try this:

static constexpr int January = 1;