Sams Teach Yourself C++ in 21 Days

(singke) #1
Creating and Using Namespaces 645

18


Defining Functions Outside a Namespace ....................................................


You should define namespace functions outside the namespace body. Doing so illustrates
a clear separation of the declaration of the function and its definition—and also keeps the
namespace body uncluttered. Separating the function definition from the namespace also
enables you to put the namespace and its embodied declarations within a header file; the
definitions can be placed into an implementation file. Listings 18.7a and 18.7b illustrate
this separation.

LISTING18.7A Declaring a Header in a Namespace


0: // file header.h
1: namespace Window {
2: void move( int x, int y) ;
3: // other declarations ...
4: }

LISTING18.7B Declaring the Implementation in the Source File


0: // file impl.cpp
1: void Window::move( int x, int y )
2: {
3: // code to move the window
4: }

Adding New Members ..................................................................................


New members can be added to a namespace only within the namespace’s body. You can-
not define new members using qualifier syntax. The most you can expect from this style
of definition is a complaint from your compiler. The following example demonstrates
this error:
namespace Window
{
// lots of declarations
}
//...some code
int Window::newIntegerInNamespace ; // sorry, can’t do this
The preceding line of code is illegal. Your (conforming) compiler issues a diagnostic
reflecting the error. To correct the error—or avoid it altogether—move the declaration
within the namespace body.
Free download pdf