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
|
#include <iostream>
#include <string>
// each enumerator is associated with a value of the underlying type (int in this case).
// when an initialiser is present, the values of enumerator is that of the initialisers.
// if the first enumerator does not have an initializer, the associated value is zero.
// for any other enumerator which does not have an initializer, the value is one greater than the value of the previous enumerator
// here, both BIRD_MIN and PEACOCK have a value of zero, SPARROW has a value of 1, both BIRD_MAX and HUMMINGBIRD have a value of 8 (CARDINAL+1)
enum bird_type { BIRD_MIN = 0, PEACOCK = BIRD_MIN, SPARROW, CANARY, PARROT, PENGUIN, OSTRICH, EAGLE, CARDINAL, BIRD_MAX = CARDINAL+1, HUMMINGBIRD = BIRD_MAX };
const std::string bird_name[] = { "PEACOCK", "SPARROW", "CANARY", "PARROT", "PENGUIN", "OSTRICH", "EAGLE", "CARDINAL", "HUMMINGBIRD" };
std::string bird_type_to_string( bird_type bird )
{
// values of type bird_type are implicitly-convertible to values of type int
if( bird >= BIRD_MIN && bird <= BIRD_MAX ) return bird_name[bird] ;
else return "UNKNOWN" ;
}
void display_bird_list() // display a list of birds
{
for( int i = BIRD_MIN ; i <= BIRD_MAX ; ++i )
{
// there is no implicit conversion from an int to bird_type, a cast is required
// the value of the int to be so converted should be within the range of the enumeration
std::cout << i << ". " << bird_name[ bird_type(i) ] << '\n' ;
}
}
int main()
{
bird_type bird = PARROT ; // Declare a variable bird of the type birdType
display_bird_list() ; // display a list of bird types
std::cout << "\nenter a number [" << BIRD_MIN << "..." << BIRD_MAX << "] for the bird type: " ;
int number = BIRD_MIN ;
std::cin >> number ; // accept a number corresponding to the bird type
if( number >= BIRD_MIN && number <= BIRD_MAX ) // if the number is within the range of the enumeration
{
bird = bird_type(number) ; // convert it to bird_type by with a cast
std::cout << "bird type is " << bird_type_to_string(bird) << '\n' ;
}
else std::cout << number << " does not correspond to a bird type\n" ;
}
|