2012-03-11 148 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