2016-11-30 85 views
1

考慮以下代碼:爲什麼我不會收到有關枚舉比較不匹配的警告?

typedef enum Type1 
{ 
    val11, 
    val12 
} Type1; 

typedef enum Type2 
{ 
    val21, 
    val22 
} Type2; 

Type1 type1 = val11; 
if (type1 == val22) 
    std::cout << "foo"; 

的Visual Studio 2015年不會發出任何警告(即使有/長城)。但type1val22不屬於同一類型。這是正常的還是Visual Studio的錯誤?

+0

如果是像C#枚舉東西只是一個整數支持,所以如果保存在C++真實它也許可以等同於'如果(TYPE1 == 1)' – Kritner

+0

這是正常的。等號運算符的兩邊都轉換爲「int」。 – Leon

+3

編寫現代C++代碼,使用'enum class'。 –

回答

0

據我所知,編譯器沒有義務在比較不同類型的枚舉時發出警告。我無法在標準中找到它。 對於傳統的枚舉類型,存在隱式類型轉換爲int,所以生成的代碼是完全合法的。 從語義上講,比較不同類型的枚舉通常是不正確的,所以既然C++有一個不允許隱式轉換的範圍枚舉結構。 (請參閱下面的代碼)。

#include <iostream> 
using namespace std; 

enum UE1 // This is an unscoped enumeration (since C) 
{ 
    val11, 
    val12 
}; 

enum UE2 // This is an unscoped enumeration too 
{ 
    val21, // have to use different names for enumeration constants 
    val22 
}; 

enum class SE1 // This is an scoped enumeration (since C++11) 
{ 
    val1, 
    val2 
}; 

enum class SE2 
{ 
    val1, // can use the same names for the constants 
    val2 // because they are in the different scope 
}; 

int main(int, char**) 
{ 
    if (val11 == val22) // implicit conversion from an enum to int is available 
     cout << "UE::val11 is equal to UE::val22" << endl; 

    if (static_cast<int>(SE1::val1) == static_cast<int>(SE2::val1)) // have to apply explicit conversion 
     cout << "SE1::val1 is equal to SE2::val1" << endl; 

    if (SE1::val1 == SE2::val1) // error!!! Cannot make implicit conversions from a scoped enumeration. 
     cout << "SE1::val1 is equal to SE2::val1" << endl; 

    return 0; 
} 
相關問題