了解'using'关键字:C++
Understanding 'using' keyword : C++
有人能解释一下下面的输出吗:
#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
关键字用于
-
快捷键名称,这样您就不需要键入
std::cout
之类的内容 -
使用模板(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,规则是实现不能只选择其中一个。您必须使用资格来解决问题。
相关文章:
- "using namespace std;"在C++的作用是什么?
- vector<vector<double>> to mxArray using memcpy
- Using C++ CryptAPI:CNG Create CSR
- STLPort using C++11
- 函数中的 c++ using 语句,后跟函数名称(对于 ADL?
- Using getchar_unlocked()
- 类作用域的类型别名"using":[何时]方法中的用法可以先于类型别名?
- 嵌套命名空间的"using"指令,但需要命名内部命名空间
- 为什么"using System;"不被视为不良做法?
- 为什么我需要做'using namespace std'而不是"使用 std::cout"?
- 'using namespace'实现细节的便捷方法(仅标头库)?
- C++中"typedef"、"using"、"namespace"和"using namespace"有什么区别?
- 在"template"和函数声明之间使用:template<typename trait> using tr = base_trait<trait> void fn(tr::t
- 如何区分C++中的"using declaration"和"using directive"?
- C++ "using tcp=x"到"namespace tcp=x"有什么区别
- 如何为流输出运算符提供重载<<模板'using'类型别名?
- Using PrimitiveBatch::DrawIndexed with ID3D11DeviceContext::
- 如何创建一个 while 循环,继续循环,直到在C++中输入'using streams'键?
- 是否可以使用 using 将基类中的公共成员重新声明为派生类中的私有成员?
- Qt3D: using Qt3DRender::QLayerFilter