在开关盒中返回bool

New*_*810 0 c++ enums switch-statement

我正在尝试在C++中切换案例和继承,并发现一些问题/警告.

例如,我有一个抽象的基本类字段:

Field.h

class Field{
  private:
  FieldType type_;

  public:
  enum FieldType
  {
    GRASS,WATER,STREET,HOME,TOWNHALL
  };
virtual bool checkIsBuildable(Fieldtype type);
Run Code Online (Sandbox Code Playgroud)

现在我在子类Buildings.cpp和Properties.cpp中收到警告:

  warning enumeration value GRASS,WATER,STREET bit handled in switch
Run Code Online (Sandbox Code Playgroud)

因为它是一个bool我只能在默认情况下返回false或true并且该方法不能正常工作或?我只想查看一下在Houses.cpp中的Home和Townhall以及Properties中的Grass,Water和street.

Buildings.cpp

bool Buildings::isBuildable(Field::FieldType type)
{    
   switch(type)
  {
    case Field::HOME:
      return true;
    case Field::TOWNHALL:
      return false;
  }
}

Properties.cpp

 bool Properties::isBuildable(Field::FieldType type)
{    
   switch(type)
  {
    case Field::GRASS:
      return true;
    case Field::WATER:
      return false;
    case Field::STREET:
      return false;
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

你需要添加default:return true; 或return false; 在这种情况下;

bool Properties::isBuildable(Field::FieldType type)
{    
   switch(type)
  {
    case Field::GRASS:
      return true;
    case Field::WATER:
      return false;
    case Field::STREET:
      return false;
    default:
      return false;

  }
}
Run Code Online (Sandbox Code Playgroud)

或者只是添加退出交换机范围:

bool Properties::isBuildable(Field::FieldType type)
{    
   switch(type)
  {
    case Field::GRASS:
      return true;
    case Field::WATER:
      return false;
    case Field::STREET:
      return false;
  }

  return false;
}
Run Code Online (Sandbox Code Playgroud)

因为如果你的类型不等于case中的一个值,那么函数将不会返回任何值,你需要借助上面显示的方法来修复它.