首页 > 解决方案 > 通过辩论的区别

问题描述

大家好我写了两个代码

1.

    #include<iostream>
    using namespace std;
    void swap(int *x, int *y)
    {
        int t;
        t = *x;
        *x = *y;
        *y = t;
    }
    int main()
    {
        int a = 10, b = 20;
        cout << "value of a before swap " << a << endl;
        cout << "value of b before swap " << b << endl;
        swap(&a, &b);
        cout << "value of a after swap " << a << endl;
        cout << "value of b after swap " << b << endl;
        cin.get();

    }

2.

    #include<iostream>
    using namespace std;
    void swap(int *x, int *y)
    {
        int t;
        t = *x;
        *x = *y;
        *y = t;
    }
    int main()
    {
        int a = 10, b = 20;
        cout << "value of a before swap " << a << endl;
        cout << "value of b before swap " << b << endl;
        swap(a, b);
        cout << "value of a after swap " << a << endl;
        cout << "value of b after swap " << b << endl;
        cin.get();

    }

在这两种情况下,我都得到与交换前 a 的值相同的输出 10 交换前 b 的值 交换 20 前 a 的值 交换 20 后交换 10 后的 b 值

我的第一个问题是 swap(&a,&b) 和 swap(a,b) 对交换函数没有影响吗?

但是当我给下面给出的交换函数提供相同的参数时

void swap(int &x, int &y)
{
    int t;
    t = x;
    x = y;
    y = t;
}

交换(a,b)没有问题并且工作正常,但是当我将值作为交换(&a,&b)传递时,代码给出错误错误C2665:'swap':3个重载都不能转换所有参数类型为什么?

标签: c++overloadingpass-by-referenceswapname-lookup

解决方案


问题是这条邪恶的线:

using namespace std;

在您的第二个示例中,您实际上是在调用::std::swap. 由于您的版本swap需要指针,因此您必须使用&运算符。

请参阅为什么是“使用命名空间标准;” 被认为是不好的做法?


推荐阅读