zoukankan      html  css  js  c++  java
  • C/C++使用心得:enum与int的相互转换

    转自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 0
    7    n = white;  // change n to 1
    8    n = blue;   // change n to 2
    9 } 

    以下代码也说明了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 1
    10    n = z;   // change n to 2
    11 } 
    但是,C++编译器并不提供从int转换成Color的自动转换:
    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,应提供强制类型转换:

    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类型有意义。
    参考链接:点击打开链接
  • 相关阅读:
    Codeforces 448 D. Multiplication Table
    编程算法
    Linux内核导出符号宏定义EXPORT_SYMBOL源代码分析
    3.Chrome数据同步服务分析--server一片
    hadoop 开始时间datanode一个错误 Problem connecting to server
    about greenplum collection tool
    HDU 3172 Virtual Friends(并用正确的设置检查)
    leetcode
    Codeforces 450 C. Jzzhu and Chocolate
    Swift
  • 原文地址:https://www.cnblogs.com/cxjchen/p/2959384.html
Copyright © 2011-2022 走看看