0

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

#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.)
4

3 回答 3

4

我还有另一个错误:

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

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

doSomethingWith(A::z);
于 2013-06-26T16:50:42.407 回答
4

using关键字用于

  1. 快捷方式名称,因此您无需键入类似的内容std::cout

  2. 使用模板(c ++ 11)进行typedef,即template<typename T> using VT = std::vector<T>;

在您的情况下,namespace用于防止名称污染,这意味着两个函数/变量意外共享相同的名称。如果将两者using一起使用,这将导致模棱两可z。我的 g++ 4.8.1 报错:

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;
     ^

这是预期的。我不确定您使用的是哪个 gnu 编译器,但这是一个可预测的错误。

于 2013-06-26T16:53:54.230 回答
2

你得到一个次优的消息。更好的实现仍然会标记错误,但说“z 是模棱两可的”,因为这是问题所在,而不是“未声明”。

在这一点上,名称 z 遇到了多个问题:A::z 和 B::z,规则是实现不能只选择其中之一。您必须使用资格来解决问题。

于 2013-06-26T16:51:10.973 回答