2017-08-10 72 views
1

爲什麼我在使用using namespace指令而不使用完全限定名稱空間的情況下在相同函數中使用兩個不同名稱空間時出現錯誤消息(錯誤:超載myCout()調用不明確)?在同一函數中使用不同名稱空間

#include <iostream> 
using namespace std; 

namespace first 
{ 
    void myCout(void) 
    { 
     cout<<"Hello World is great\n"; 
    } 
} 

namespace second 
{ 
    void myCout(void) 
    { 
     cout<<"Hello Sky is high\n"; 
    } 
} 

    int main(void) 
    { 

     cout<<"Hello World\n"; 
     using namespace first; 
      myCout(); 

     using namespace second; 
      myCout(); 

     return(0); 
    } 

如果我在第二個命名空間使用完全合格的命名空間爲myCout()如下面給出的,沒有問題

int main(void) 
{ 
    cout<<"Hello World\n"; 
    using namespace first; 
    myCout(); 
    second::myCout(); 
    return(0); 
} 
+0

你'使用第二個命名空間後,',有myCout'的'2點的定義,與相同的簽名,在'main'的範圍內,因此 - 調用是不明確的。 –

回答

5

using指令尊重範圍。所以,你可以引入一個新的塊範圍來限制每個引入的符號的可用性:

int main(void) 
{ 
    cout<<"Hello World\n"; 
    { 
     using namespace first; 
     myCout(); 
    } 

    { 
     using namespace second; 
     myCout(); 
    } 

    return(0); 
} 

正常,從而避免衝突和深度嵌套,嘗試只是你需要用一個using標識符拉而不是聲明。例如如果你只曾經想使用foo類從first那麼就不會有用以下毫不含糊:

using first::foo; 
using namespace second; 
3

using namespace ...指令不創建一個有序的路徑;也不會覆蓋以前的所有內容。所以,是的,你的代碼創建了一個模糊的情況。

1

首先您使用namespace first,因此引入了第一個名稱空間的myCout。然後您使用namespace second,導致其他myCout也發揮作用。第二個命名空間不會覆蓋以前的命名空間

因此,當您第二次致電myCout時,有兩個定義在起作用,導致編譯器將此定義爲不明確的調用。

換句話說:

int main(void) 
{ 
    using namespace first; // `myCout` of the 1st namespace is introduced 
    myCout(); 

    using namespace second; // `myCout` of the 2nd namespace is introduced 
    // and does not override the first namespace! 

    myCout();    // Which `myCout`? Of the first or second? 

    return 0; 
} 
相關問題