Creating and Using Namespaces 651
18
int value3 = 60 ;
}
//...
using Window::value2 ; //bring value2 into current scope
Window::value1 = 10 ; //value1 must be qualified
value2 = 30 ;
Window::value3 = 10 ; //value3 must be qualified
The usingdeclaration adds the specified name to the current scope. The declaration does
not affect the other names within the namespace. In the previous example,value2is ref-
erenced without qualification, but value1and value3require qualification. The using
declaration provides more control over namespace names that you bring into scope. This
is in contrast with the directive that brings all names in a namespace into scope.
After a name is brought into a scope, it is visible until the end of that scope. This behav-
ior is the same as any other declaration. A usingdeclaration can be used in the global
namespace or within any local scope.
It is an error to introduce a duplicate name into a local scope in which a namespace
name has been declared. The reverse is also true. The following example shows this:
namespace Window
{
int value1 = 20 ;
int value2 = 40 ;
}
//...
void f()
{
int value2 = 10 ;
using Window::value2 ; // multiple declaration
std::cout << value2 << std::endl ;
}
The second line in function f()produces a compiler error because the name value2is
already defined. The same error occurs if the usingdeclaration is introduced before the
definition of the local value2.
Any name introduced at local scope with a usingdeclaration hides any name outside
that scope. Consider the following code snippet:
namespace Window
{
int value1 = 20 ;
int value2 = 40 ;
}
int value2 = 10 ;
//...
void f()