首页 > 解决方案 > 在开关盒中返回布尔值

问题描述

我正在尝试在 C++ 中切换大小写和继承,并发现了一些问题/警告。

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

Field.h

class Field{
  private:
  FieldType type_;

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

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

  warning enumeration value GRASS,WATER,STREET bit handled in switch

由于它是一个布尔值,我只能在默认情况下返回 false 或 true,并且该方法无法正常工作,或者?我只想检查 Buildings.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;
  }
}

标签: c++enumsswitch-statement

解决方案


您需要添加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;

  }
}

或者只是将 return 添加到 switch 范围之外:

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;
}

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


推荐阅读