当我写下面的代码就被编译并正确执行:为什么在全局范围和局部范围内使用指令的行为有所不同?
#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
和之外使用指令时,使用指令的行为会有所不同?
谢谢Jesse的快速回复......请纠正我,如果我错了......但是当使用指令在主函数中仍然会有2个y的声明。如果是这样,为什么编译器只能在第二种情况下出现问题? – Amrit
@ user2235938:有两个'y'的声明,但using-declaration在main内部声明'second :: y',而first :: y'在全局命名空间范围内声明。由于'second :: y'在main中被声明,它隐藏了'first :: y'。你熟悉名称隐藏吗? –
对不起杰西......但我无法理解。当两个语句“首先使用命名空间; using second :: y;”在main函数内部,它应该在本地作用域中声明first :: y和second :: y,并给出编译错误。但它并没有和程序编译和运行成功。当两种语句都是主要的时候,由于含糊不清,它甚至不会被编译。请解释... – Amrit