|
C M S C 2 1 4 C o m p u t e r S c i e n c e I I F a l l 2 0 0 2 |
However, in C++, you can't name two classes the same name because the names would class. Class names are in the same namespace. To deal with this problem, C++ has introduced C++ namespaces. You should have read about that in Project 0.
Another way to deal with the namespace problem is to use nested classes. This makes sense when you have a class that seems subservient to another class. Thus, if you have a "linked list" class, you can think of a node as being a class that belongs to "linked list".
However, you can't easily name a class Node. Why not? Suppose you want a singly linked list, a doubly linked list, and a circularly linked list. You like the name Node, but you can't use it for all three classes, because there would be a namespace clash.
To indicate this class, you write the outer class name first, followed by two colons, followed by the nested class name. Thus, you can have DLL::Node, and SLL::Node, and the two types are different.
If the nested class is in the private section of the header file, then only methods in the class may access those objects. In particular, you should avoid using the nested class as a parameter or return value in a public method (but you can use private nested class objects inside the method itself, where the user can't see it). You should be able to use private nested objects in private methods, however, since they are only acccessible inside the class.
If the nested class is declared in the public section of the header file, then you can declare objects of that type outside the class. Thus, SLL::Node could be declared and used.
Nested classes are used by the STL for iterators.
The only tricky part about using nested classes is trying to write out the name of the class. In particular, constructors can be a pain to write.
Here's an example:
// copy constructor
SLL::Node::Node( const SLL::Node & other )
{
// code
}
// operator=
SLL::Node & SLL::Node::operator=( const SLL::Node & other )
{
// code
}
The syntax is weird. Basically, nested class members start with SLL::Node followed by two colons, and the name of the method.
You can often refer to Node by the shorter name (i.e, Node instead of SLL::Node), especially within the class itself. C++ tends to assume that if you declare a type, that it refers to a nested class, if it exists. If the compiler complains, you can always use the longer name.
It's often best to think about the two classes as separate classes, despite one being nested inside the other.
|
See the class syllabus for policies concerning email Last Modified: Fri Sep 13 20:11:45 EDT 2002 |
|
|
|
|
|