我有以下代码:
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <conio.h>
#include <cstring>
#include <iomanip>
void swap(long a, long b)
{
long temp;
temp=a;
a=b;
b=temp;
}
int _tmain(int argc, _TCHAR* argv[])
{
int x = 5, y = 3;
cout << x ;
cout << y << endl;
swap(x, y);
cout << x ;
cout << y << endl;
getch();
return 0;
}
程序提供输出:
5 3
3 5
该程序实际上交换价值!这是为什么? swap()
的参数不是指针或引用。
(我正在使用VS 2005)
答案 0 :(得分:37)
根本没有调用swap
函数。
标准库中包含的一个标准库正在引入<utility>
,它在swap
命名空间中声明了一个名为std
的函数模板。由于您是using namespace std;
,因此swap
函数将被带入全局命名空间,而是调用它。
为什么选择std::swap
而不是swap
功能?您的swap
函数按值获取两个long
;要调用该函数,每个int
参数都需要进行整数提升。
std::swap
是一个功能模板。它需要对T
进行两次引用,并且当使用T = int
实例化该函数模板时,两个参数都是完全匹配的。因此,std::swap
是比您的函数更好的匹配,因此在重载解析期间选择它。
这是using namespace std;
邪恶的一个原因,应该避免。如果你删除using指令,你的函数将是唯一可用的函数,它将被调用。
答案 1 :(得分:1)
说long
而不是int
。
您当前的代码已经更好地匹配swap
,因此它避免了隐式转换为long
,而是使用了STL内置的swap
。
在旁注中,使用语言D中的overload sets(也是here)可以解决这种歧义。