【问题标题】:Why does this program swap the values?为什么这个程序交换值?
【发布时间】:2011-08-20 15:07:18
【问题描述】:

我有以下代码:

#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)

【问题讨论】:

标签: c++ swap argument-dependent-lookup name-lookup


【解决方案1】:

您的 swap 函数根本没有被调用。

您所包含的标准库之一是引入&lt;utility&gt;,它在std 命名空间中声明了一个名为swap 的函数模板。由于您是 using namespace std;,因此 swap 函数被带入全局命名空间并被调用。


为什么选择std::swap 而不是您的swap 函数?您的 swap 函数需要两个 longs 的值;要调用该函数,每个int 参数都需要一个整数提升。

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


这是using namespace std; 是邪恶的,应该避免的原因之一。如果你删除 using 指令,你的函数将是唯一可用的函数,它将被调用。

【讨论】:

  • 你可以通过 ::swap(x, y) 调用你 swap()
【解决方案2】:

long 而不是int

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

顺便说一句,使用语言 D 中的overload sets(也称为here)在一定程度上解决了这种歧义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    相关资源
    最近更新 更多