简体   繁体   中英

Understanding 'using' keyword : C++

Can someone please explain below output:

#include <iostream>

using namespace std;

namespace A{
    int x=1;
    int z=2;
    }

namespace B{
    int y=3;
    int z=4;
    }

void doSomethingWith(int i) throw()
{
    cout << i ;
    }

void sample() throw()
{
    using namespace A;
    using namespace B;
    doSomethingWith(x);
    doSomethingWith(y);
    doSomethingWith(z);

    }

int main ()
{
sample();
return 0;
}

Output:

$ g++ -Wall TestCPP.cpp -o TestCPP
TestCPP.cpp: In function `void sample()':
TestCPP.cpp:26: error: `z' undeclared (first use this function)
TestCPP.cpp:26: error: (Each undeclared identifier is reported only once for each function it appears in.)

I have another error:

error: reference to 'z' is ambiguous

Which is pretty clear for me: z exists in both namespaces, and compiler don't know, which one should be used. Do you know? Resolve it by specifying namespace, for example:

doSomethingWith(A::z);

using keyword is used to

  1. shortcut the names so you do not need to type things like std::cout

  2. to typedef with templates(c++11), ie template<typename T> using VT = std::vector<T>;

In your situation, namespace is used to prevent name pollution, which means two functions/variables accidently shared the same name. If you use the two using together, this will led to ambiguous z . My g++ 4.8.1 reported the error:

abc.cpp: In function ‘void sample()’:
abc.cpp:26:21: error: reference to ‘z’ is ambiguous
     doSomethingWith(z);
                     ^
abc.cpp:12:5: note: candidates are: int B::z
 int z=4;
     ^
abc.cpp:7:5: note:                 int A::z
 int z=2;
     ^

which is expected. I am unsure which gnu compiler you are using, but this is an predictable error.

You get a suboptimal message. A better implementation would still flag error, but say 'z is ambiguous' as that is the problem rather than 'undeclared'.

At the point name z hits multiple things: A::z and B::z, and the rule is that the implementation must not just pick one of them. You must use qualification to resolve the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM