FAQ 15.03 How can code outside a namespace use names declared within that namespace?

graphics/new_icon.gif

One way to use a declaration from a namespace is, for every occurrence, to use the scope operator :: to prefix the name declared in the namespace with the name of the namespace. For example,

 namespace People {   int fred = 2;   int wilma = 3; } void f() throw() {   int i = People::fred + People::wilma; } 

Another approach is to to introduce the equivalent of a local name with what is known as a using declaration. The function f() from the previous example could be written as

 void f2() throw() {   using People::fred;      // Use People's fred   int i = fred + People::wilma; } 

Another approach is called a using directive. Using this idea, the function f() from the previous example could be written as

 void f3() throw() {   using namespace People;   // Declare all names from People   int i = fred + wilma; } 

Note that a using directive does not declare any variables; it merely makes names available.

Finally, notice that the global namespace can be thought of as the namespace without an identifier (i.e., ::fred refers to fred in the global namespace).



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net