C++ 为什么这个程序要交换这些值?

C++ 为什么这个程序要交换这些值?,c++,swap,argument-dependent-lookup,name-lookup,C++,Swap,Argument Dependent Lookup,Name Lookup,我有以下代码: #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,

我有以下代码:

#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;
}
程序实际上交换了这些值!为什么呢?
swap()
的参数不是指针或引用


(我正在使用VS2005)

您的
交换功能根本没有被调用

您包含的标准库之一是拉入
,它在
std
命名空间中声明了名为
swap
的函数模板。因为您使用的是
名称空间std
,该函数将被引入全局命名空间,并被调用


为什么选择了
std::swap
而不是
swap
功能?您的
swap
函数按值取两个
long
s;要调用该函数,每个
int
参数都需要整数提升

std::swap
是一个函数模板。它引用了两个
T
,当该函数模板用
T=int
实例化时,两个参数都是完全匹配的。因此,
std::swap
比您的函数更匹配,因此在重载解析期间选择它



这是
使用名称空间std的一个原因是邪恶的,应该避免。如果删除using指令,您的函数将是唯一可用的函数,它将被调用。

long
,而不是
int

您当前的代码已经与
swap
有了更好的匹配,因此它避免了隐式转换为
long
,而是使用STL中内置的
swap

另一方面,这种歧义在某种程度上是通过使用语言D解决的。

您可以通过::swap(x,y)调用swap()。基本上,这是一个重复,尽管除非您知道答案,否则您不会知道这一点。
5 3

3 5