传递参数之间的区别

Difference between passing an arguement

大家好我写了两个代码

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 交换 20 后 a 的值 交换后 b 的值 10

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

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

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

swap(a,b) 没有问题并且工作正常但是当我将值作为 swap(&a,&b) 代码给出错误 错误 C2665:'swap':3 个重载中的 none 可以转换所有参数类型 为什么??

问题是这条邪恶的线:

using namespace std;

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

Why is “using namespace std;” considered bad practice?

1和2肯定有区别

  1. 您正在获取专门用于(保存)您的变量 a 的实际保留内存的地址,这没关系,您可以有效地交换它们的内容。

  2. 您认为 a 和 b 的值是有效地址,但我可以向您保证的是 OS 不会让您在正常使用中访问这些特定区域,因此地址错误,程序以 SEGFAULT 结尾,这是 NOK。

在第一个程序中调用了您自己的指针交换函数。

在第二个程序中,由于不合格的名称查找和 using 指令的存在,为 int 类型的对象调用了标准函数 std::swap

在第三个程序中(当您提供 ab 时)调用了您自己的函数 swap,它通过引用接受类型为 int 的对象。如果模板函数和非模板函数都合适,编译器更喜欢使用非模板函数。

但是你第四个程序中的swap函数并不是为了交换指针而设计的。所以编译器试图select一个标准的交换函数std::swap。但它不是为了交换临时(右值)对象而设计的。所以编译器报错。

如果引入了包含指向变量 ab.

的指针的中间变量,则可以调用标准交换函数

这是一个演示程序。

#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;
    int *pa = &a;
    int *pb = &b;

    cout << "value of *pa before swap " << *pa << endl;
    cout << "value of *pb before swap " << *pb << endl;

    swap( pa, pb); 

    cout << "value of *pa after swap " << *pa << endl;
    cout << "value of (pb after swap " << *pb << endl;

    cin.get();

}

它的输出是

value of *pa before swap 10
value of *pb before swap 20
value of *pa after swap 20
value of (pb after swap 10  

在这个程序中,你自己的函数 swap 没有被调用,因为它的参数是对类型 int 对象的引用,但你正在调用 swap 传递类型 int * 的对象(指针)。

因此调用了专门用于 int * 类型对象的标准函数 std::swap

它交换指针本身而不是指针指向的对象..