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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
|
Enumerations hi(enumeration: nested) hi(nested enumerations) may also be
nested in classes. Nesting enumerations is a good way to show the close
connection between the enumeration and its class. Nested enumerations have the
same controlled visibility as other class members. They may be defined in the
private, protected or public sections of classes and are inherited by derived
classes. In the class ti(ios) we've seen values like tt(ios::beg) and
tt(ios::cur). In the current i(Gnu) bf(C++) implementation these values are
defined as values of the ti(seek_dir) enumeration:
verb(
class ios: public _ios_fields
{
public:
enum seek_dir
{
beg,
cur,
end
};
};
)
As an illustration assume that a class tt(DataStructure) represents a data
structure that
may be traversed in a forward or backward direction. Such a class can define
an enumeration tt(Traversal) having the values tt(FORWARD) and
tt(BACKWARD). Furthermore, a member function tt(setTraversal) can be defined
requiring a tt(Traversal) type of argument. The class can be defined as
follows:
verb(
class DataStructure
{
public:
enum Traversal
{
FORWARD,
BACKWARD
};
setTraversal(Traversal mode);
private:
Traversal
d_mode;
};
)
Within the class tt(DataStructure) the values of the tt(Traversal)
enumeration can be used directly. For example:
verb(
void DataStructure::setTraversal(Traversal mode)
{
d_mode = mode;
switch (d_mode)
{
FORWARD:
break;
BACKWARD:
break;
}
}
)
Ouside of the class tt(DataStructure) the name of the enumeration type is
not used to refer to the values of the enumeration. Here the classname is
sufficient. Only if a variable of the enumeration type is required the name of
the enumeration type is needed, as illustrated by the following piece of code:
verb(
void fun()
{
DataStructure::Traversal // enum typename required
localMode = DataStructure::FORWARD; // enum typename not required
DataStructure ds;
// enum typename not required
ds.setTraversal(DataStructure::BACKWARD);
}
)
Only if tt(DataStructure) defines a nested class tt(Nested), in
turn defining the enumeration tt(Traversal), the two class scopes are
required. In that case the latter example should have been coded as follows:
verb(
void fun()
{
DataStructure::Nested::Traversal
localMode = DataStructure::Nested::FORWARD;
DataStructure ds;
ds.setTraversal(DataStructure::Nested::BACKWARD);
}
)
|