为什么我的枚举比较不匹配时没有收到任何警告?

13 浏览
0 Comments

为什么我的枚举比较不匹配时没有收到任何警告?

这个问题已经有答案了:

为什么枚举类优于普通枚举?

考虑以下代码:

typedef enum Type1
{
    val11,
    val12
} Type1;
typedef enum Type2
{
    val21,
    val22
} Type2;
Type1 type1 = val11;
if ( type1 == val22 )
    std::cout << "foo";

Visual Studio 2015不会发出任何警告(即使使用/Wall)。 然而, type1 和 val22 不是同一类型。 这是正常的还是 Visual Studio 的错误?

admin 更改状态以发布 2023年5月20日
0
0 Comments

据我所知,编译器在比较不同类型的枚举时没有发出警告的义务。我在标准中找不到这个要求。\n对于经典的枚举类型,存在隐式的类型转换为int,所以结果代码是完全合法的。\n从语义上讲,比较不同类型的枚举通常是不正确的,因此自C ++以来,我们使用了一个作用域枚举构造,它不允许隐式转换。(请参见下面的代码)。\n

#include 
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(SE1::val1) == static_cast(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;
}

0