C/C++使用心得:enum與int的相互轉換

來源:互聯網
上載者:User

 

轉自http://blog.csdn.net/lihao21/article/details/6825722

如何正確理解enum類型?

例如:

1 enum Color { red, white, blue}; 2 Color x;

 

我們應說x是Color類型的,而不應將x理解成enumeration類型,更不應將其理解成int類型。

 

我們再看enumeration類型:

1 enum Color { red, white, blue};

 

(C程式員尤其要注意!)

理解此類型的最好的方法是將這個類型的值看成是red, white和blue,而不是簡單將看成int值。
C++編譯器提供了Color到int類型的轉換,上面的red,
white和blue的值即為0,1,2,但是,你不應簡單將blue看成是2。blue是Color類型的,可以自動轉換成2,但對於C++編譯器來
說,並不存在int到Color的自動轉換!(C編譯則提供了這個轉換)

例如以下代碼說明了Color會自動轉換成int:

1 enum Color { red, white, blue };2  3 void f()4 {5    int n;6    n = red;    // change n to 07    n = white;  // change n to 18    n = blue;   // change n to 29 } 

 

以下代碼也說明了Color會自動轉換成int:

 1 void f() 2 { 3    Color x = red; 4    Color y = white; 5    Color z = blue; 6   7    int n; 8    n = x;   // change n to 0 9    n = y;   // change n to 110    n = z;   // change n to 211 } 

 

但是,C++編譯器並不提供從int轉換成Color的自動轉換:
1 void f()2 {3    Color x;4    x = blue;  // change x to blue5    x = 2;     // compile-time error: can't convert int to Color6 } 

 

若你真的要從int轉換成Color,應提供強制類型轉換:

1 void f()2 {3    Color x;4    x = red;      // change x to red5    x = Color(1); // change x to white6    x = Color(2); // change x to blue7    x = 2;        // compile-time error: can't convert int to Color8 } 

 

但你應保證從int轉換來的Color類型有意義。

 

參考連結:點擊開啟連結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.