C++指针和引用的区别

C++指针和引用的区别



指针、引用程序实践

源代码

#include <iostream>

using namespace std;

void maopapOrder(int arr[]){

        for(int i=0;i<2;i++){
        for(int j=0;j<2-i;j++){
            if(arr[j]>arr[j+1]){
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
}

void orderMethod1(int a,int b,int c){
    int arr[3] = {a,b,c};
    maopapOrder(arr);
    a = arr[0];
    b = arr[1];
    c = arr[2];
    cout << "inside int type : " << a << " " << b <<  " " << c << endl;

}

void orderMethod2(int* a,int* b,int* c){
    int arr[3] = {*a,*b,*c};
    maopapOrder(arr);
    *a = arr[0];
    *b = arr[1];
    *c = arr[2];

    cout << "inside int* type : " << *a << " " << *b <<  " " << *c << endl;

}

void orderMethod3(int& x,int& y,int& z){
    int arr[3] = {x,y,z};
    maopapOrder(arr);
    x = arr[0];
    y = arr[1];
    z = arr[2];

    cout << "inside int& type : " << x << " " << y <<  " " << z << endl;

}



int main()
{
    int a = 0;
    int b = 0;
    int c = 0;

    cout << "please input three integer values:" << endl;

    cin >> a >> b >> c;

    orderMethod1(a,b,c);
    cout << "outside int type : " << a << " " << b<<  " " << c << endl;
    cout << "-----------------------------------------" << endl;
/*
    orderMethod2(&a,&b,&c);
    cout << "outside int* type : " << a << " " << b<<  " " << c << endl;
    cout << "-----------------------------------------" << endl;
*/
    orderMethod3(a,b,c);
    cout << "outside int& type : " << a << " " << b<<  " " << c << endl;
    cout << "-----------------------------------------" << endl;







    return 0;
}

输出结果:

指针:
指针

引用:

引用

结果分析

从定义上讲
指针是一个变量,变量中保存的是某个对象的地址,指向内存中的某个存储单元。
引用实际上与它所绑定的变量共用一块内存空间,是它绑定的那个变量的一个别名。
从使用规则上讲
指针可以有多级指针,而引用只能有一级
指针可以不初始化,指向NULL,而引用在使用时必须初始化。
从作为函数参数传递上
值得注意的是,二者皆可达到通过函数中的操作修改原变量值的效果,只是:
指针作为函数参数时,要求变量将地址传入,对指针的指向值的修改就是对原变量值的修改。
引用作为函数参数时,可以理解为就是将原变量传入(因为二者共用一块内存空间),对引用的修改当然也可以等效到引用绑定的原变量上。

但是,引用本身不需要开辟空间,所以在运行的时空效率上更好。

更多相关内容请参见

我的博客

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值