乐闻世界logo
搜索文章和话题

How to convert enumeration to int in c++

1个答案

1

In C++, an enum type is a user-defined type consisting of a set of named integer constants. The conversion from enum to int in C++ is implicit, meaning you can directly assign an enum value to an int variable or use the enum value where an int is required.

Example

Suppose we have an enum type representing the days of the week:

cpp
enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

In this enum, Sunday is implicitly assigned the value 0, Monday 1, and so on, up to Saturday as 6. If you want to convert this enum type to an int type, you can do the following:

cpp
Day today = Day::Friday; int dayNumber = today; // Automatically converts the enum to int

In this example, dayNumber will get the value 5 because Friday corresponds to the 5th element in the enum (counting from 0).

Explicit Conversion

Although the conversion from enum to int is typically implicit, you can use static_cast to explicitly represent this conversion if you want to be more explicit:

cpp
Day today = Day::Tuesday; int dayNumber = static_cast<int>(today);

This code more explicitly expresses your intent to consciously convert from an enum type to an integer type.

Enum Class (C++11 and later)

If you are using C++11 or later, you can use enum class, which is a strongly typed enum that does not implicitly convert to other types. To convert an enum class member to int, you must use explicit conversion:

cpp
enum class Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }; Day today = Day::Monday; int dayNumber = static_cast<int>(today); // Must use explicit conversion

In this case, without using static_cast, the code will not compile because enum class does not support implicit type conversion.

In summary, whether using traditional enum types or enum class, converting enum values to int is straightforward, though explicit or implicit conversion may be required depending on the syntax.

2024年7月28日 11:45 回复

你的答案