如何使用C++检查此条件

How to check this condition with C++

本文关键字:条件 检查 C++ 何使用      更新时间:2023-10-16

Class Direction

class Direction
{
public:
 enum value
 {
  UP,
  RIGHT,
  DOWN,
  LEFT,
  STAY
 };
};   

类点

 #include "Direction.h"
        class Point {
         int x , y;
        public:
         Point() { x=0; y=0; };
         Point(int x1 , int y1) : x(x1) , y(y1) {};
         void setX(int newX) { x = newX; };
         void setY(int newY) { y = newY; };
         int getX() { return x; }
         int getY() { return y; }
         void move(Direction d) {
          if(d==UP);
        };

问题是if(d==UP)我不明白如何检查条件,我收到检查这个错误。

有什么想法吗?任何帮助将不胜感激。

UPclass Direction 内声明,因此在该范围之外,您应该编写Direction::UP来引用它:

if (...something... == Direction::UP)
    ...

Direction类创建value枚举类型,但尚没有任何数据成员,因此不清楚您可能要在d中与Direction::UP进行比较。 您可以通过在 class Direction 中的最后一个};之前插入额外的行来添加数据成员:

value value_;

那么你的比较将变成:

if (d.value_ == Direction::UP)
    ...

综上所述,如果你的class Direction除了enum之外不包含任何其他内容,你可以考虑完全去掉类部分,简单地单独声明枚举:

enum Direction { UP, ... };

然后,您的比较将简化为:

if (d == UP)
    ...

我认为您不需要创建类Direction。简单的枚举就足够了。

enum class Direction
{
    UP,
    DOWN,
    LEFT,
    RIGHT,
    STAY,
};

然后你可以编写与以下类似的函数:

void do_move(Direction d)
{
    switch (d) {
    case Direction::LEFT:
        cout << "LEFT" << endl;
        break;
    case Direction::RIGHT:
        cout << "RIGHT" << endl;
        break;
    case Direction::UP:
        cout << "UP" << endl;
        break;
    case Direction::DOWN:
        cout << "DOWN" << endl;
        break;
    case Direction::STAY:
        cout << "STAY" << endl;
        break;
    default:
        break;
    }
}

简单地称之为:

Direction d = Direction::UP;
do_move(d);
do_move(Direction::STAY);

你真正想要的是Direction成为一个枚举,而不是一个类:

enum Direction { UP, RIGHT, DOWN, LEFT, STAY };

现在你可以像这样简单地调用move

move(UP);

您的if(d==UP);将按预期工作。

我注意到你的Direction类除了一个枚举之外什么都没有,在这种情况下,你可以简单地:

enum class Direction {
  UP,
  ...
};

区别在于枚举将封装在其中enum class。你仍然需要做if (d == Direction::UP).

如果将其设置为常规枚举:

enum Direction {
  UP,
  ...
};

然后,您可以像原始代码一样直接if (d == UP)

此外,这样您就可以拥有比value dDirection::value d更显眼的Direction d

你现在拥有的是一个常规枚举,它没有封装在value中,而是封装在value所在的Direction类中。您只能直接在 Direction 内部解决它,但在它之外,您必须指定封装类的作用域。

if(d.value == UP)

d 属于 class Direction 型,而不是 Enum value 型。因此,您无法比较d和"UP"