Enumerations (enum) used to create a C ++ constants. Suppose it is necessary to declare constants for each of musical notes and initialize the appropriate serial number. You can use the familiar us way:
This declaration takes a lot of lines of code and is not convenient. Using enumeration, you can define these constants otherwise. Syntax enum similar to the syntax structures: keyword – descriptor – elements in braces, separated by commas:
This is the full form – with a descriptor (the name of the enumeration). As in the case with structures, the name of an enumeration, you can not use:
In the first case – We can create variables of type enumnotes. In the second case, – no.
Note, that the value 1 was given only to the first enumeration member. By default, the first item in the braces are assigned a value 0, the second one more than (1), the third one more second (2) etc. But if you explicitly set the value, as in the example, the increase in the unit will begin with this number. We will show on the screen the values of some elements of the enumeration.
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <iostream> using namespace std; enum notes{ DO = 1, RE, MI, FA, SOL, LA, SI }; int main() { setlocale(LC_ALL, "rus"); cout << DO << ' ' << RE << ' ' << SOL << endl; return 0; } |
Although we have not explicitly been assigned a value RE and SOL– they keep the correct serial numbers of notes.
The names of enumerators (enumeration members) must be unique. The values may also be the same:
1 | enum champions{ KLICHKO_VITALIY = 1, KLICHKO_VLADIMIR = 1, CHISORA, ADAMEK }; |
Value 1 will keepKLICHKO_VITALIY andKLICHKO_VLADIMIR. 2 written inCHISORA, 3 – inADAMEK . In the enumeration elements can only be written to integers. Change in the program following values, are assigned to the elements in curly brackets can not be. If you create a variable of type enum – it can only take the value of one of its elements:
The picture shows, that record number in a variable of type champions is not possible. You can only record a named constant, which is declared at the time of determination enum.
For example, consider fixing. In it create a transferlevelsName. It will contain six elements – “name” floors. User offer“go for a drive” on the elevator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | #include <iostream> using namespace std; enum levelsName { parking, bank, insurance, exchange, showroom, Restaurant }; int main() { setlocale(LC_ALL, "rus"); int floor = parking; // выбор пользователя - номер этажа int exitOrNot = 1; // выйти или нет while (exitOrNot == 1) { cout << "Номер этажа (0,1,2,3,4,5): "; cin >> floor; switch (floor) { case(parking) : cout << "\a\a\aВы в паркинге!\n\n"; break; case(bank) : cout << "\a\a\aПервый этаж!"; cout << "\nЗдесь находится Креди Агриколь Банк.\n\n"; break; case(insurance) : cout << "\a\a\aВторой этаж!"; cout << "\nСтраховая компания UNICA.\n\n"; break; case(exchange) : cout << "\a\a\aТретий этаж!"; cout << "\nФондовая биржа.\n\n"; break; case(showroom) : cout << "\a\a\aЧетвёртый этаж!"; cout << "\nВыставочный зал и зал для презентаций.\n\n"; break; case(Restaurant) : cout << "\a\a\aПятый этаж!"; cout << "\nРесторан Sky.\n\n"; break; default: cout << "\a\a\aОшибка!\n\n"; } cout << "Выйти из лифта - нажмите 0.\n"; cout << "Выбрать другой этаж - нажмите 1: "; do { cin >> exitOrNot; } while (exitOrNot != 0 && exitOrNot != 1); cout << endl; } return 0; } |
We declare an integer variable floor in string 10 and initialize it named constantparking. So floor will value 0. In string 13 enter in a while loop. As long as the user enters into a variableexitOrNot value 0, the program will offer him “ride the elevator” – select the number of the floor.
After each selection floors alarm sounds (three short beeps) and displays the floor number, and information about, that is placed on it. This is done selection switch statement. His blockscase sorted enumerationg elements. That is, the user enters an integer, andcase looking for, any of the elements of the enumeration it corresponds.
For example, if introduced 5 – this corresponds to an elementRestaurant – displays a message.
Result:
Watch a short video on the transfers C ++.
Normal examples, and I did not read the article.
I formulate, as you please straighten, if Article I broke up in something.
1) Magic numbers – This is bad, to get rid of them using constant.
2) constants – it's good, but the constants are strongly connected with each other.
Example: the program we have a unit. A unit can be a magician, goblin or elf. One embodiment of this might be something:
const int Mag = 1;
const int Goblin = 2;
const int Elf = 3;
struct Unit {
string name;
int unit_type;
};
obviously, This is bad, because:
2.1) constant Mag, Goblin, Elf available to all, i.e.. pollute the namespace;
2.2) constants can be randomly used in the wrong context, because they are not grouped, i.e.. It is no different from other constants;
2.3) unit_type field, you can assign the wrong value (the compiler does not tell us about an error) :
unit.unit_type = -123;
2.4) We need to invent themselves values of constants and monitor so that they do not recur.
All these problems erotic decides enum:
enum UnitType { Mag, Goblin, Elf };
struct Unit {
unit_type type;
string name;
};
refer to the constants we can both directly (Mag) and enumeration named (UNITTYPE::Mag). The second option is clearly the context indicates, but it seems to appear in C ++ 11 (earlier it maintained most compilers, but standard like as it is not consistent with).
unit.unit_type = 123;
will fail at compile time (i.e.. too early). And if you uzing modern IDE – the earlier (IDE will underline error).
Well, the values assigned to them automatically, follow this is not necessary.
The code can be made a bit prettier:
struct Unit {
unum Type {Mag, Goblin, Elf} type;
string name;
};
This may be better, tk. it is seen, that Unit and Type inextricably linked (before we encode it in the name UnitType). Encode something in the name is not very good, for example if the Unit be renamed the Item – we would have to rename ItemType, or a bond would not obvious.
Unit::Type::Mag succinctly sets the context, wherein the constant can be used.
But even unum widely used templates, but that's another topic. You open your it? )
My version of solving the problem of Example:
pre class=”only:c++ decode:true ”
#include
using namespace std;
int main()
{
setlocale(LC_ALL, “rus”);
enum lewels {undParking = -1, oneFloor = 1, secondFloor = 2, Restaurant = 3, Penthouse = 4};
int lift = 0;
int exit = 1;
cout <<"Вы зашли в здание и сейчас находитесь на " << oneFloor << " этаже \n";
do
{
cout <> lift;
switch (lift)
{
case(undParking):
cout << "Вы попали в подземную автостоянку \n";
break;
case(oneFloor):
cout << "Вы на первом этаже \n";
cout <> exit;
if (exit == 0)
{
cout << "Вы вышли из здания \n";
}
break;
case(secondFloor):
cout << "Вы на втором этаже \n";
break;
case(Restaurant):
cout << "Вы в ресторане \n";
break;
case(Penthouse):
cout << "Вы в пентхаусе \n";
break;
default:
cout << "Нет такого этажа \n";
}
} while (exit == 1);
return 0;
}
/pre
Enumeration in C ++ directly inherit the behavior of C transfers, except, that enum type in C ++ - true type, and a keyword
A quote from the description of the C and C ++ languages:
> The S89 version is defined 32 keywords.
> …
> enum - User-defined data type “enumerated type”
> …
> In C ++ contains all keywords, defined in the S89 version, as well as the following.
Where is the difference here?
If for each enumeration case the value is set (known as "raw" value), this value can be a string, a character or value of any integer or floating point type.