如何通过C 的开关运行类枚举

How to run a class enum through a switch in C++

本文关键字:运行 枚举 开关 何通过      更新时间:2023-10-16

我有两个彼此平行的类。第一个是房间,第二个是船。在船上,我必须使用房间课检查是否有效。我正在运行开关语句,因为我使用不同的条目做不同的事情。问题在于,从房间进入开关语句的定义变量是枚举,并且编译器不喜欢。

这就是我拥有的

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())。注意括号。