我在 C++ 中尝试切换大小写和继承,发现了一些问题/警告。
例如我有一个抽象基础类Field:
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
因为它是一个 bool 值,我只能在默认情况下返回 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
;或 返回 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 out of 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 中的值之一,那么函数将不会返回任何值,您需要借助上面显示的方法来修复它。
关于c++ - 在开关盒中返回 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50133543/