如何通过C 的开关运行类枚举
How to run a class enum through a switch in C++
我有两个彼此平行的类。第一个是房间,第二个是船。在船上,我必须使用房间课检查是否有效。我正在运行开关语句,因为我使用不同的条目做不同的事情。问题在于,从房间进入开关语句的定义变量是枚举,并且编译器不喜欢。
这就是我拥有的
bool Ship::checkRoom ( const Room& theRoom )
{
switch (theRoom.getType)
供参考,这是" getType"称为:
inline RoomType getType() const { return mType; };
您可以将类枚举值传递给Switch语句。但是您需要调用函数:
switch (theRoom.getType())
这是一个工作示例:
enum class FOO { A, B };
struct Foo
{
FOO getFoo() const { return FOO::A; }
};
int main()
{
Foo f;
switch (f.getFoo())
{
case FOO::A:
case FOO::B:
break;
default:
break;
}
}
您将功能传递给switch
,而不是enum
。因此,您应该调用该函数以在交换机中使用其返回值。
长话短说 - 你错过了括号。
switch (theRoom.getType)
需要
// --------------------vv
switch (theRoom.getType())
you can 在C 中的枚举上开关,因为它们是积分类型。实际上,这很有用,因为您可以在情况标签中使用枚举器值,这使您的程序更清晰。
您拥有的本质上是错字: theRoom.getType
是该函数的地址,其数据类型不应该打开。
您需要使用switch (theRoom.getType())
。注意括号。
相关文章:
- 不带大括号的枚举形式
- 枚举环境变量的惯用C++14/C++17方法
- 类似枚举的计算常量
- 如何正确实现和访问运算符的各种自定义枚举器
- 错误:从"int"到枚举c++的转换无效
- C++中构造函数中的枚举
- 访问在 C++ 结构中声明的枚举变量
- 枚举类'classname'的多重定义
- 强枚举类型定义:Clang Bug 还是 C++11 标准不确定性?
- typedef 枚举和枚举类有什么区别?
- 为什么我的开关/机箱在使用枚举时默认?
- 在运行时使用枚举器值作为模板函数的模板参数的元程序
- 如何设计运行时分配值枚举?
- C++运行时从编译时已知集/枚举中选择模板非类型参数
- 如何通过C 的开关运行类枚举
- 在C++中如何将运行时类型鉴别器映射到模板实例(无需手动枚举所有实例)
- 枚举上的重载<<运算符会导致运行时错误
- 在运行时有条件地声明枚举(C++)
- 枚举和类——运行时错误!
- 在运行时解析枚举模板参数