[英]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 class
在enum
。
關於“為什么不只是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.