在switch语句中使用const int变量 [英] Using const int variable in switch statement

查看:300
本文介绍了在switch语句中使用const int变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有-std = c ++ 11标志的gcc。在我的班级定义中,我有以下内容:

  private:
const int一月= 1,
二月= 2,
三月= 3,
...

在我的实现中我有一个switch语句。

  switch(currentMonth)
{
case January:
returnString =一月;
休息时间;
案例二月:
returnString = February;
休息时间;
案例三月:
returnString = March;
休息时间;
...

这似乎应该工作,因为月份是固定的;但是,gcc给了我

  calendar.cpp:116:12:错误:这不是常量表达式
在每个switch语句的情况下都是

。为什么会这样?

解决方案

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

 静态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;

这篇关于在switch语句中使用const int变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆