当我编写以下代码时,它会被正确编译和执行:
#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;
}
但是,如果我在 main 函数之外使用指令编写如下,
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
谁能解释为什么 using 指令在内部main
和外部使用时表现不同main
?