Sams Teach Yourself C++ in 21 Days

(singke) #1
When you add new members, you do not want to include access modifiers, such as pub-
lic or private. All members encased within a namespace are public. The following code
does not compile because you cannot specify private:
namespace Window
{
private:
void move( int x, int y ) ;
}

Nesting Namespaces ......................................................................................


A namespace can be nested within another namespace. The reason they can be nested is
because the definition of a namespace is also a declaration. As with any other name-
space, you must qualify a name using the enclosing namespace. If you have nested
namespaces, you must qualify each namespace in turn. For example, the following shows
a named namespace nested within another named namespace:
namespace Window
{
namespace Pane
{
void size( int x, int y ) ;
}
}
To access the function size()outside of the Windownamespace, you must qualify the
function with both enclosing namespace names. In this case, you need to use the follow-
ing line to access size:
Window::Pane::size( 10, 20 ) ;

Using a Namespace..............................................................................................


Let’s take a look at an example of using a namespace and the associated use of the scope
resolution operator. In the example, all types and functions for use within the namespace
Windoware declared. After everything required is defined, any member functions that
were declared are defined. These member functions are defined outside of the name-
space; the names are explicitly identified using the scope resolution operator. Listing
18.8 illustrates using a namespace.

LISTING18.8 Using a Namespace
0: #include <iostream>
1: // Using a Namespace
2:
3: namespace Window

646 Day 18

Free download pdf