当我写下以下代码时,它可以被正确地编译和执行:
#include <iostream>
using namespace std;
namespace first
{
int x = 5;
int y = 10;
}
namespace second
{
double x = 3.1416;
double y = 2.7183;
}
int main () {
using namespace first; //using derective
using second::y;
cout << x << endl;
cout << y << endl;
return 0;
}
但如果我像下面这样在主函数外使用指令:
using namespace first; //using derective
using second::y;
int main () {
cout << x << endl;
cout << y << endl;
return 0;
}
它会产生这个编译错误:
g++ namespace03.cpp -o namespace03
namespace03.cpp: In function ‘int main()’:
namespace03.cpp:20:11: error: reference to ‘y’ is ambiguous
namespace03.cpp:13:10: error: candidates are: double second::y
namespace03.cpp:7:7: error: int first::y
make: *** [namespace03] Error 1
能否有人解释一下,为什么在main
内和main
外使用编译指示符会有不同的行为?
y
有两个声明,但是using-declaration在main函数内声明了second::y
,而first::y
则在全局命名空间范围内声明。由于second::y
在main函数内声明,它会隐藏first::y
。你是否熟悉名称隐藏? - Jesse Goodusing second::y
隐藏了first::y
。就像在不同作用域中声明两个同名变量一样,内部作用域中声明的变量会隐藏外部作用域中的变量。 - Jesse Good