Evgenii Legotckoi
Evgenii LegotckoiSept. 2, 2017, 7:25 a.m.

C++ - Tutorial 008. Enumerations

In addition to classes, C ++ supports enumerations. In the current standard, C ++ is supported as enumeration without the scope that was introduced in earlier versions of C ++, as well as C.

enum ColorTypes {
    Green,
    Yellow,
    Red
};

So enumerations with scope

enum class ColorTypes {
    Green,
    Yellow,
    Red
};

The difference between enumerations and scope from enumeration without scope

The difference between an enumeration and a scope is different from an enumeration without scope in that the enumeration variables with the scope can not be implicitly converted to integer variables and vice versa. For this conversion, use static_cast () .

enum class ColorTypes { Green, Yellow, Red };

ColorTypes currentType_1 = ColorTypes::Green; // Ok
ColorTypes currentType_2 = 2; // Error, conversion is impossible
int currentType_3 = ColorTypes::Red; // Error, conversion is impossible
int currentType_4 = Red; // Error, Red does not exist in this scope
int currentType_5 = static_cast<int>(ColorTypes::Green);

Such scope control allows you to declare enums in the class whose members have the same names. Also provides more control over the code, although it imposes a number of limitations.

How to Set Enumeration Values

By default, the enumeration starts at 0, and the enumeration of the members of the enumeration continues ...

enum class ColorTypes {
    Green,      // 0
    Yellow,     // 1
    Red,        // 2
    Black,      // 3
    Blue        // 4
};

but you can set your own values for enumerations when you declare.

enum class ColorTypes {
    Green = 15,                 // 15
    Yellow,                     // 16
    Red = 24,                   // 24
    Black = ColorTypes::Red,    // 24
    Blue                        // 25
};

Using switch case for enumerations

Enumerations with both scope and scope are supported by the condition and branch operators switch / case :

ColorTypes currentType = ColorTypes::Green;

switch (currentType)
{
    case ColorTypes::Green: std::cout << "Green"; break;
    case ColorTypes::Yellow: std::cout << "Yellow"; break;
    case ColorTypes::Black: std::cout << "Black"; break;
    case ColorTypes::Blue: std::cout << "Blue"; break;
    default: std::cout << "Unknown Type"; break;
}

If you talk about control of code execution and imposed restrictions when using enumerations with scope and without scope, you can simulate the situation when in switch / case for some reason (typo, copy-paste, noob, screwed up when resolving conflicts with the merge of branches) There are enumerations of different types. Then enumerations without scope are implicitly converted to the required type by the compiler and the code is executed, although it will be erroneous, and in the case of enumerations, the compiler will report an error and stop building the program.

That is, below, the following code, being erroneous, will be compiled:

enum SideTypes {
    Top,
    Bottom,
    Right,
    Left
};

enum ColorTypes {
    Green = 8,
    Yellow,
    Red,
    Blue
};

int main(int argc, char *argv[])
{
    ColorTypes currentType = ColorTypes::Green;

    switch (currentType)
    {
        case SideTypes::Top: std::cout << "Top Side"; break;
        case ColorTypes::Green: std::cout << "Green"; break;
        case ColorTypes::Yellow: std::cout << "Yellow"; break;
        case ColorTypes::Red: std::cout << "Red"; break;
        case ColorTypes::Blue: std::cout << "Blue"; break;
        default: std::cout << "Unknown Type"; break;
    }

    return 0;
}

At best, the compiler will throw Warning.

warning: case value ‘0’ not in enumerated type ‘ColorTypes’ [-Wswitch]
         case SideTypes::Top: std::cout << "Top Side"; break;
         ^

But sometimes it happens that the programmer "knows the C ++ better than the compiler" and disables warnings.

While the following code is simply not compiled:

enum class SideTypes {
    Top,
    Bottom,
    Right,
    Left
};

enum class ColorTypes {
    Green = 8,
    Yellow,
    Red,
    Blue
};

int main(int argc, char *argv[])
{
    ColorTypes currentType = ColorTypes::Green;

    switch (currentType)
    {
        case SideTypes::Top: std::cout << "Top Side"; break;
        case ColorTypes::Green: std::cout << "Green"; break;
        case ColorTypes::Yellow: std::cout << "Yellow"; break;
        case ColorTypes::Red: std::cout << "Red"; break;
        case ColorTypes::Blue: std::cout << "Blue"; break;
        default: std::cout << "Unknown Type"; break;
    }
    return 0;
}

The compiler will generate a compilation error:

error: could not convert ‘Top’ from ‘SideTypes’ to ‘ColorTypes’
         case SideTypes::Top: std::cout << "Top Side"; break;
                         ^

How to specify a specific integer type for enumeration

Enumerations can also have a more specific type, which must be a specific integer type:

  • unsigned char;
  • char;
  • int;
  • long int;
  • etc.

This allows you to allocate a certain amount of memory to variables that have enumeration values. Perhaps this may be relevant for embedded development. Depending on the target platform, a certain amount of memory will be allocated.

enum class SideTypes : short int {
    Top,
    Bottom,
    Right,
    Left
};

Iterator for enumerations

And finally, we'll make an iterator for the enumerations, with which we can use the range-based loop .

#include <iostream>

enum class ColorTypes
{
    Blue,
    Red,
    Green,
    Purple,
    First=ColorTypes::Blue,   // participant of the enumerator for the first element
    Last=ColorTypes::Purple // participant of the enumerator for the last item
};

ColorTypes operator++(ColorTypes& x)
{
    // std::underlying_type converts the type of ColorTypes into an integer type, under which the given enum was declared
    return x = static_cast<ColorTypes>(std::underlying_type<ColorTypes>::type(x) + 1);
}

ColorTypes operator*(ColorTypes c)
{
    return c;
}

ColorTypes begin(ColorTypes r)
{
    return ColorTypes::First;
}

ColorTypes end(ColorTypes r)
{
    ColorTypes l=ColorTypes::Last;
    return ++l;
}

int main(int argc, char *argv[])
{
    // We use parentheses to instantiate the enumeration
    for(const auto& c : ColorTypes())
    {
        std::cout << static_cast<int>(c) << std::endl;
    }

    return 0;
}
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

ДК
  • Nov. 26, 2019, 9:38 a.m.
  • (edited)

классная статья! Большое спасибо. Хотел бы добавить для тех, кто будет использовать это в другом классе- перед операторами и методами begin(), end() нужно поставить friend.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
MB

Qt - Test 001. Signals and slots

  • Result:57points,
  • Rating points-2
MB

C++ - Test 001. The first program and data types

  • Result:60points,
  • Rating points-1
GK

C++ - Test 005. Structures and Classes

  • Result:0points,
  • Rating points-10
Last comments
J
JonnyJoJune 8, 2023, 12:14 p.m.
Qt/C++ - Lesson 019. How to paint triangle in Qt5. Positioning shapes in QGraphicsScene Евгений, здравствуйте! Решил поэкспериментировать немного с кодом из этого урока, нарисовать вместо треугольника квадрат и разобраться с координатами. В итоге, запутался. И ни документация,…
J
JonnyJoMay 25, 2023, 2:24 p.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, благодарю!
Evgenii Legotckoi
Evgenii LegotckoiMay 25, 2023, 4:49 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Код на строчка 184-198 вызывает перерисовку области на каждый 4-й такт счётчика. По той логике не нужно перерисовывать объект постоянно, достаточно реже, чем выполняется игровой слот. А слот вып…
J
JonnyJoMay 21, 2023, 10:49 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, благодарю! Всё равно не совсем понимаю :( Если муха двигает ножками только при нажатии клавиш перемещение, то что, собственно, делает код со строк 184-198 в triangle.cpp? В этих строчка…
Evgenii Legotckoi
Evgenii LegotckoiMay 21, 2023, 5:57 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Добрый день. slotGameTimer срабатывает по таймеру и при каждой сработке countForSteps увеличивается на 1, это не зависит от нажатия клавиш, нажатая клавиша лишь определяет положение ножек, котор…
Now discuss on the forum
T
TwangerJune 7, 2023, 11:12 a.m.
Ошибка при выполнении триггерной функции (GreenPlum) Есть 3 таблицы fact_amount со структурой: CREATE TABLE fact_amount ( id serial4 NOT NULL, fdate date NULL, type_activity_id int4 NULL, status_id int4 NULL, CONSTRAINT fact…
AR
Alexander RyabikovJune 6, 2023, 1:35 p.m.
Работа с QFileSystemModel Вопросик по теме QFileSystemModel в Linux. Он, как и положено, обновляется самостоятельно, если директория локальная. Но, вот, сетевая папка (у меня шара samba) не обновляется. Как её можно…
Evgenii Legotckoi
Evgenii LegotckoiApril 16, 2023, 4:07 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Да, это возможно. Но подобные вещи лучше запускать через celery. То есть drf принимает команду, и после этого регистрирует задачу в celery, котроый уже асинхронно всё это выполняет. В противном …
АБ
Алексей БобровDec. 14, 2021, 7:03 p.m.
Sorting the added QML elements in the ListModel I am writing an alarm clock in QML, I am required to sort the alarms in ascending order (depending on the date or time (if there are several alarms on the same day). I've done the sorting …

Follow us in social networks