FAQ 15.04 What happens if two namespaces contain the same name?

graphics/new_icon.gif

Suppose two different namespaces have their own versions of class string. Both namespaces can be introduced into the same code fragment without conflict, as long as there are no unqualified references to string. However, if there are unqualified references to string, the compiler issues an error because the unqualified name string is ambiguous. This is illustrated in the following example.

 namespace A {   int x = 1;   int z = 2; } namespace B {   int y = 3;   int z = 4; } void doSomethingWith(int i) throw(); void sample() throw() {   using namespace A;                                 <-- 1   using namespace B;                                 <-- 2   doSomethingWith( x );                              <-- 3   doSomethingWith( y );                              <-- 4   doSomethingWith( A::z );                           <-- 5   doSomethingWith( B::z );                           <-- 6   #ifdef GENERATE_ERROR     doSomethingWith( z );                            <-- 7   #endif } main() { sample(); } 

(1) OK: Introduces A::x and A::z

(2) OK: Introduces B::y and B::z

(3) OK: Unqualified x unambiguously resolves to A::x

(4) OK: Unqualified y unambiguously resolves to B::y

(5) OK: The A:: qualifications makes this unambiguous

(6) OK: The B:: qualifications makes this unambiguous

(7) Error: Ambiguous: A::z or B::z?



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