2013-03-21 34 views
3

我想比較兩個枚舉值,但在運行時它似乎總是評估爲真。在Table.h比較枚舉類型時的邏輯錯誤

枚舉聲明與迴歸方法獲取的狀態值:

enum TableStatus { IDLE, SEATED, ORDERED, SERVED}; 

class Table 
    { 
    private: 
      ... 
      TableStatus status;  // current status 
    public: 
      ... 
      TableStatus getTableStatus(void); 
    } 

在我需要比較枚舉值我一直在嘗試條件語句看起來像下面的部分:

if (tables[tableId]->getTableStatus() == TableStatus(SERVED)) 

我的問題如何讓這個邏輯工作。在比較Table對象的狀態到某個枚舉值將正確評估。

編輯:包括getTableStatus(void);

TableStatus Table::getTableStatus(void){ 
     return status; 
} 
+1

您顯示的代碼對於您描述的任務是正確的。如果'getTableStatus()'總是返回'SERVED',那麼在其他地方有個bug。 – 2013-03-21 18:09:27

回答

2

當我使用枚舉時遇到了同樣的困惑。有幾次,我必須查找關於枚舉的教程,以確保我是正確的。當我使用枚舉進行編程時,我閱讀了這個(http://www.cprogramming.com/tutorial/enum.html)教程。

基本上枚舉(C++ 98)的行爲不像類,所以你寫的是不正確的。 枚舉可以直接引用,所以你必須寫:

if (tables[tableId]->getTableStatus() == SERVED) 

提供枚舉和你在哪裏寫代碼的功能在同一個範圍內。

如果您使用的是C++ 11,則enum classes是更好的選擇。我喜歡枚舉類,因爲我不會像C++ 98枚舉那樣與它們混淆。 http://www.cprogramming.com/c++11/c++11-nullptr-strongly-typed-enum-class.html

+0

感謝您的快速響應。 – 2013-03-21 18:32:59