有人可以解释下面的输出:

#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;
}


输出:

$ 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.)

最佳答案

我还有另一个错误:


  错误:对“ z”的引用不明确


这对我来说很清楚:z在两个名称空间中都存在,并且编译器不知道应该使用哪个名称空间。你知道吗?通过指定名称空间来解决它,例如:

doSomethingWith(A::z);

关于c++ - 了解'using'关键字:C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17325920/

10-11 22:55
查看更多