1. An enumeration is a distinct type. With
enum colour_t { /* ... */ }; colour_t is a distinct integral type - the type of
colour_t is different from
char,
int etc.
2. The values that can be used are restricted to one of a set of named constants.
With
enum colour_t { RED, GREEN, BLUE, BLACK };, a variable of type
colour_t can take only one of the values
RED,
GREEN,
BLUE,
BLACK
3. Each of those constant values is an integral value.
By default, the values are
RED = 0, GREEN = RED+1, BLUE = GREEN+1, BLACK = GREEN+1
4. We can change the default by explicitly specifying an integral value for an enumeration.
enum colour_t { RED = 1, GREEN = 2, BLUE = 4, BLACK = 0 };
5. Each of the enumerations can be implicitly converted to an integral type.
The value of
GREEN in the above example converted to an integer is the integer 2.
6. However, any integral value can't be converted to a
colour_t.
If we have an integer 4, it is the value of
BLUE and we can convert it to a
colour_t via an explicit cast;
1 2
|
colour_t clr = RED ;
clr = colour_t(4) ; // clr will get a value of BLUE
| |
7. Since an enumeration is a distinct type,
std::cin does not know how to read it.
It knows all about reading
char,
int etc., but nothing about reading a
colour_t
8. However, we can read an
int using
std::cin, and if the integer has a value of 1, 2, 4 or 0, we can cast it safely to a
colour_t
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
|
#include <iostream>
int main()
{
// answer_type is a distinct type
// the range of values it can have is add, sub, ..., invalid
// add can be converted to the integral value int('+') etc.
enum answer_type { add = '+', sub = '-' , mul = '*' , div = '/',
pow = '^', sqrt = 'r', invalid = 0 } ;
std::cout << "? (+,-,*,/,^,r): " ;
char input ; // input is a char
std::cin >> input ; // fine; std::cin knows how to read a char
// answer is not a char, it is a variable pof type answer_type
answer_type answer ;
switch(input)
{
case add: // add is implicitly converted to '+'
// the user has entered '+' as the input
std::cout << "addition\n" ;
// therefore, the answer is add or answer_type('+')
answer = answer_type(input) ;
break ;
// case sub : etc.
default:
// the chyar that the user has entered is not the value of
// one of the enumerations add, sub etc.
std::cerr << input << "is an invalid operation\n" ;
answer = invalid ;
}
// ...
}
| |
You might want to peruse a tutorial or two; for instance this one:
http://www.cprogramming.com/tutorial/enum.html