2013-07-19 35 views
3

看來,「使用函數名」只能隱藏普通函數,但不能隱藏操作數的友元函數或操作數的相同名稱空間中的函數。我是否正確理解這一點?「使用函數名」只能隱藏普通函數?

例1:

void swap(int) 
{ 

} 

void foo() 
{ 
    using std::swap; 
    int i=10,j=20; 
    swap(i); //compile error ,because std::swap hidden void swap(int) 
} 

例2:

class Cat { 
    friend void swap(Cat&, Cat&); 
}; 
void swap(Cat &lhs, Cat &rhs) 
{ 
    cout<<"call cat friend swap"<<endl; 
} 

class Foo 
{ 
    public: 
     Cat h; 
}; 

void swap(Foo &lhs, Foo &rhs) 
{ 
    using std::swap; 
    swap(lhs.h, rhs.h); //compile ok. will print out 
         //call cat friend swap 
} 
+4

是的,這是真的。 'using'在本地引入了一個名字,它將名字隱藏在名字空間中。但是名稱搜索也使用依賴於參數的查找,該查找仍然有效(並可能會查找一些隱藏的名稱)。如果你想查找'std :: swap'而沒有其他東西,那就寫'std :: swap(i);'。 –

+0

@BenVoigt應該是一個()的答案。 – TemplateRex

+0

@TemplateRex:我期待這個被標記爲重複。 –

回答

2

你的觀察是正確的。

using在本地級別引入了一個名稱,它將名稱隱藏在名稱空間中。但是名稱搜索也使用依賴於參數的查找,該查找仍然有效(並可能會查找一些隱藏的名稱)。如果你想找到std::swap而沒有別的,那麼寫std::swap(i);