简体   繁体   English

了解'using'关键字:C ++

[英]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 错误:对“ z”的引用不明确

Which is pretty clear for me: z exists in both namespaces, and compiler don't know, which one should be used. 这对我来说很清楚: z在两个名称空间中都存在,并且编译器不知道应该使用哪个名称空间。 Do you know? 你知道吗? Resolve it by specifying namespace, for example: 通过指定名称空间来解决它,例如:

doSomethingWith(A::z);

using keyword is used to using关键字用于

  1. shortcut the names so you do not need to type things like std::cout 快捷方式名称,因此您无需键入诸如std::cout

  2. to typedef with templates(c++11), ie template<typename T> using VT = std::vector<T>; 使用模板(c ++ 11)进行typedef,即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. 在您的情况下, namespace用于防止名称污染,这意味着两个函数/变量意外共享同一名称。 If you use the two using together, this will led to ambiguous z . 如果将两者一起using ,则会导致z模棱两可。 My g++ 4.8.1 reported the error: 我的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;
     ^

which is expected. 这是预期的。 I am unsure which gnu compiler you are using, but this is an predictable error. 我不确定您使用的是哪个gnu编译器,但这是可预见的错误。

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'. 更好的实现仍然会标记错误,但是说“ z模棱两可”是问题所在,而不是“未声明”。

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. 在这一点上,名称z会遇到多个问题:A :: z和B :: z,并且规则是实现不能只选择其中之一。 You must use qualification to resolve the issue. 您必须使用资格来解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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