在开关盒中返回bool

时间:2018-05-02 11:24:57

标签: c++ enums switch-statement

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

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

STR

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

text

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

Field.h

class Field{
  private:
  FieldType type_;

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

1 个答案:

答案 0 :(得分:5)

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

  }
}

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

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中的一个值,那么函数将不会返回任何值,你需要借助上面显示的方法来修复它。

相关问题