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

Understanding 'using' keyword : C++

本文关键字:C++ using 了解 关键字      更新时间:2023-10-16

有人能解释一下下面的输出吗:

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

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编译器,但这是一个可预测的错误。

您会得到一条次优消息。更好的实现仍然会标记错误,但要说"z不明确",因为这就是问题所在,而不是"未声明"。

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