簡體   English   中英

以下聲明之間的區別?

[英]Difference between the following declarations?

我有枚舉類型,顏色:

enum colors {green, red, blue};

colors mycolors=red是否與int yourcolors=red相同,並且每個枚舉數的類型是否為int 兩者的值都為1,對吧?

謝謝!

我只想發布一些代碼片段來證明Jason Lang和Kerrek SB的評論:

#include <iostream>
#include  <typeinfo>
enum colors {green, red, blue};

int main()
{   
    colors mycolors=red;
    int yourcolors=red;
    if (mycolors == yourcolors)
        std::cout << "same values" << std::endl;

    if (typeid(mycolors) != typeid(yourcolors))
        std::cout << "not the same types" << std::endl;

    return 0;
}

運行此代碼將導致以下控制台輸出:

same values
not the same types

另外(如Daniel Kamil Kozar所述),還有enum class (僅C ++ 11和更高版本!)。 這個問題有關為何喜歡更多信息enum classenum

關於“為什么不只是int (或long或...)之后的enum ”的問題,請考慮運算符重載。 那就是++ colors(green) == 1一定不正確。 確認以下問題 :對於普通enum可能會發生運算符重載; 此問題以及已接受的答案,以了解如何避免在“枚舉類”的重載運算符中進行強制轉換。

最后要記住, enum的用法(如果合理使用)會提高代碼的可讀性。

  • 我認為enum似乎有點類型安全。 您可以int yourcolors=red ,但不能為colors mycolors=1
  • 在調試時,枚舉用法很有幫助。 它顯示枚舉名稱而不是其值。
  • 枚舉值不是左值。 因此,當您通過引用傳遞它們時,不使用靜態內存。 幾乎就像您將計算值作為文字傳遞一樣。

enum KEYS
{
    UP,
    RIGHT,
    DOWN,
    LEFT
};

void (KEYS select)
{
    switch (select)
    {
        case UP:
        case RIGHT:
        case DOWN:
        case LEFT: break;
        default: exit(1);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM