c++ - 在开关盒中返回布尔值
问题描述
我正在尝试在 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;
}
}
解决方案
您需要添加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 中的某个值,那么函数将不会返回任何值,您需要借助上面显示的方法来修复它。
推荐阅读
- dictionary - Vue 全球词典
- android - 尽管调用了 adapterlist.clear() ,但有时会得到空的 RecyclerVew 项目
- javascript - 停止 div 从大小增加中重叠另一个
- php - 遍历数组数组生成不需要的输出
- powershell - 在 cmd 提示符下使用管道运行 PowerShell cmd
- eclipse - 为什么复合由文本字段扩展?
- javascript - NodeJS 项目中 Jsonata 模块的使用
- python - 如何使用 Keras OCR 示例推断新图像?
- c# - 无法从复制的像素创建新位图
- ruby-on-rails - 如何在 activeadmin 中添加 ajax 自动搜索集合?