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


如何正確理解enum類型?


例如:

[cpp]  view plain  copy
 
  1. enum Color { red, white, blue};   
  2. Color x;  


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

 

我們再看enumeration類型:

[cpp]  view plain  copy
 
  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:

[cpp]  view plain  copy
 
  1. enum Color { red, white, blue };  
  2.    
  3. void f()  
  4. {  
  5.    int n;  
  6.    n = red;    // change n to 0  
  7.    n = white;  // change n to 1  
  8.    n = blue;   // change n to 2  
  9. }   


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

[cpp]  view plain  copy
 
  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 1  
  10.    n = z;   // change n to 2  
  11. }   


但是,C++編譯器並不提供從int轉換成Color的自動轉換:

[cpp]  view plain  copy
 
  1. void f()  
  2. {  
  3.    Color x;  
  4.    x = blue;  // change x to blue  
  5.    x = 2;     // compile-time error: can't convert int to Color  
  6. }   

 

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

[cpp]  view plain  copy
 
  1. void f()  
  2. {  
  3.    Color x;  
  4.    x = red;      // change x to red  
  5.    x = Color(1); // change x to white  
  6.    x = Color(2); // change x to blue  
  7.    x = 2;        // compile-time error: can't convert int to Color  
  8. }   


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

參考鏈接: 點擊打開鏈接
版權聲明:本文為博主原創文章,轉載請注明出處: leehao.me https://blog.csdn.net/lihao21/article/details/6825722


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM