Namespace confusion

I am new to namespaces and tried to use this from C ++ Primer

#include<iostream>
namespace Jill 
{
 double bucket;
 double fetch;
 struct Hill{ };
}

double fetch;

int main()
{
 using namespace Jill;
 Hill Thrill;
 double water = bucket; 
 //double fetch; //<<<<<<<<<<<<//
 std::cin>> fetch;
 std::cin>> ::fetch;
 std::cin>> Jill::fetch;
 std::cout<<"fetch is "<<fetch;
 std::cout<<"::fetch is "<< ::fetch;
 std::cout<<"Jill::fetch is "<< Jill::fetch;
}

int foom()
{
 Jill::Hill top;
 Jill::Hill crest;
}

When the line marked //<<<<<<<<<<<<//is not commented out, I get the expected results. those. The variable localhides globaland Jill::fetch. But when I comment on this, there are 2 selections on the left. global fetchand Jill::fetch. And the compiler gives an error

namespaceTrial1.cpp:17:13: error: reference tofetchis ambiguous
namespaceTrial1.cpp:9:8: error: candidates are: double fetch
namespaceTrial1.cpp:5:9: error:                 double Jill::fetch
namespaceTrial1.cpp:20:26: error: reference tofetchis ambiguous
namespaceTrial1.cpp:9:8: error: candidates are: double fetch
namespaceTrial1.cpp:5:9: error:                 double Jill::fetch

My question is , why is the compiler getting confused , does this lead to ambiguity? Why it doesn’t accept fetchas soon Jill::fetchas I added using namespace Jillat the beginningmain()

using Jill::fetch; main, . using Jill::fetch , . , local fetch. [ ?] using declaration , ​​ , using directive doesnt?

+5
4

using , . [namespace.udir] p2:

(3.4.1) , , -, .

, , . using , , Jill , Jill , . ( , , , , .)

, , . .

namespace Outer {
  namespace Mid1 { int i = 1; }
  namespace Mid2 {
    namespace Tricky {
      int i = 2;
      namespace Inner {
        void f() {
          using namespace Mid1;
          std::cout << i;
        }
      }
    }
  }
}

2, 1, using , i. , Mid1, using, Outer, Mid1::i , Outer. Outer::i, Tricky::i, Mid1::i .

- . .

+3

, global/namespace, . , using, .

( 7.3.4, 3):

using , .

( , 6):

, , .

+4

using namespace , , .

- : . , Jill , , , . , .

+3

[basic.scope.declaration] , ,

int j = 24;
int main() {
int i = j, j;
j = 42;
}

j ( ). j . j j , () ,}. j (j ) {}, i. j .

, .

If a local variable is not declared, you have a name clash. The compiler cannot decide which one fetchto choose and throws an error.

+2
source

All Articles