学习记录(1)-引用传递 值传递 地址传递

    xiaoxiao2021-12-03  37

    同样对于交换两个数的值

    1.引用传递:函数原型声明:void swap(int &a,int &b)

                           函数定义:swap(int &a,int &b){

                                                    int temp;

                                                    temp=a;

                                                    a=b;

                                                    b=temp;

                                                }

                           函数调用:swap(a,b);

    2.值传递:函数原型声明:void swap(int a,int b)

                        函数定义:swap(int a,int b){

                                                    int temp;

                                                    temp=a;

                                                    a=b;

                                                    b=temp;

                                                } 

                             函数调用:swap(a,b);

    3.地址传递:函数原型声明:void swap(int *p,int *q)

                           函数定义:swap(int *p,int *q){

                                                    int temp;

                                                    temp=*p;

                                                    *p=*q;

                                                    *q=temp;

                                                } 

                           函数调用:swap(&a,&b);

    值传递并不会改变两个变量的值,而引用传递相当于别名,因此改变了两个数的值
    转载请注明原文地址: https://ju.6miu.com/read-680204.html

    最新回复(0)