交换函数(值传递,地址传递,引用作为函数参数)

本段程序主要是完成值交换函数,包括基于值传递、基于地址传递以及引用作为函数参数三个子函数。
尤其值得关注如何把引用作为函数参数,进而实现数值交换。这一段的代码如下:

void swap_y(int &a, int &b)
{
    int temp = a;
    a = b;
    b = temp;
}

全部代码以及运行效果如下:可以发现,仅仅是值传递,不能使主函数内实现数值交换,其余两种可以实现。

#include <iostream>

using namespace std;

void swap_value(int a, int b)
{
    int temp = a;
    a = b;
    b = temp;
}

void swap_ptr(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

void swap_y(int &a, int &b)
{
    int temp = a;
    a = b;
    b = temp;
}

int main(int argc, char **argv)
{
    int num1 = 10, num2 = 20;
    int x = 1, y = 2;
    int a = 100, b = 200;
    // 1 值传递
    cout << "值传递前:" << endl;
    cout << "num1 = " << num1 << endl;
    cout << "num2 = " << num2 << endl;
    swap_value(num1,num2);
    cout << "值传递后:" << endl;
    cout << "num1 = " << num1 << endl;
    cout << "num2 = " << num2 << endl;
    cout << endl;

    // 2 地址传递
    cout << "地址传递前:" << endl;
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;
    swap_ptr(&x, &y);
    cout << "地址传递后:" << endl;
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;
    cout << endl;

    // 3 引用
    cout << "引用前:" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    swap_y(a,b);
    cout << "引用后:" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    cout << endl;

    return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值