當我寫下面的代碼就被編譯並正確執行:爲什麼在全局範圍和局部範圍內使用指令的行爲有所不同?
#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