[英]How to check this condition with enums - C++
班級方向
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
不同的是, enum class
將封裝在其中。 if (d == Direction::UP)
您仍然必須做。
如果將其設為常規枚舉:
enum Direction {
UP,
...
};
然后,您可以直接按照原始代碼中的if (d == UP)
進行操作。
同樣,通過這種方式,您可以使Direction d
比value d
或Direction::value d
更加明顯。
你現在有什么是正枚舉未封裝的value
,但被封裝在Direction
類,其中value
是。 您只能在Direction
內部直接解決它,但在它外部,您必須指定封裝類的范圍。
if(d.value == UP)
d是Type class Direction
而不是Enum value
類型。 因此,您無法比較d
和`UP
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.