如何使用C++检查此条件
How to check this condition with C++
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)
我不明白如何检查条件,我收到检查这个错误。
有什么想法吗?任何帮助将不胜感激。
UP
在 class 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 d
或Direction::value d
更显眼的Direction d
你现在拥有的是一个常规枚举,它没有封装在value
中,而是封装在value
所在的Direction
类中。您只能直接在 Direction
内部解决它,但在它之外,您必须指定封装类的作用域。
if(d.value == UP)
d 属于 class Direction
型,而不是 Enum value
型。因此,您无法比较d
和"UP"
- 检查C++中的条件
- 如何在C++中使用 HRESULT 条件检查
- Vulkan 的传输队列系列功能和显卡支持:条件检查是否准确?
- 如何在多个 Catch2 测试用例中检查相同的条件
- 对于检查 >=0 终止条件时的循环索引类型
- "is defined"宏检查及其调用必须处于不同的条件下吗?
- 如果条件检查,多个向量大小相等
- 在矢量中使用特定条件检查唯一元素
- 如何根据一组规则/条件检查一组数据以进行分类
- 对类的模板(例如HashSet+HashMap)的签名进行条件检查
- 不同的条件检查方式
- 条件检查:if(x==0) vs. if(!x)
- if(!getline(std::cin,str1))break;这个条件检查什么
- 二维数组、IF条件检查
- C++程序在使用 if 条件检查指针是否为 NULL 时崩溃
- 为什么我的 OR 条件检查匹配项的字符串总是返回 true
- 使用try-Catch异常处理程序和if-else条件检查之间的区别
- 对c++中的命令行参数进行条件检查
- 如果条件检查是否有错误
- 在语句中设置条件检查格式"if"最佳方法