2012-03-11 197 views
-1
#include <iostream> 
using namespace std; 


template < class T > 
void swap (T& a, T& b) 
{ 
    T temp = a; 
    a = b; 
    b = temp; 
} 

int main() 
{ 
    char a = 'a'; 
    char b = 'b'; 
    swap (a, b); 
    cout << "a = " << a << endl; 
    cout << "b = " << b << endl; 
    return 0; 
} 

該代碼不能在linux下編譯KDE命令行(gcc編譯器)。 但是,如果我改變「使用名稱空間標準」到「使用std :: cout;使用std :: cin使用std :: endl」程序可以編譯和運行良好。它出什麼問題了? 非常感謝您無法編譯

+0

你得到了什麼*確切*錯誤信息? – 2012-03-11 16:24:43

+2

也許如果你提到它爲什麼「不能編譯」?像...錯誤信息?我們不是千里眼。 – 2012-03-11 16:24:45

+0

只需使用** std :: cout **而不是** cout **,同樣當您使用**使用命名空間標準** – DumbCoder 2012-03-11 16:25:19

回答

3

這裏是VC++說:

error C2668: 'swap' : ambiguous call to overloaded function 
1>   c:\lisp\other\test_meth\test_meth.cpp(7): could be 'void swap<char>(T &,T &)' 
1>   with 
1>   [ 
1>    T=char 
1>   ] 
1>   c:\program files (x86)\microsoft visual studio 10.0\vc\include\utility(100): or  'void std::swap<char>(_Ty &,_Ty &)' 
1>   with 
1>   [ 
1>    _Ty=char 
1>   ] 
1>   while trying to match the argument list '(char, char)' 

的問題是:STD命名空間已經包含模板函數swap。

+0

我明白了,非常感謝! – user1252725 2012-03-12 03:37:21

7

你的swap定義與std::swap已有的定義相沖突,當你在使用using namespace全局命名空間帶來std。當您嘗試實例化模板時發生衝突

注意,您可以使用

::swap (a, b); 

明確地選擇你的定義。

+0

我明白了。非常感謝你! – user1252725 2012-03-12 03:36:58