C/CPLUS

一文搞懂C++引用的好处

2022-01-30  本文已影响0人  LabVIEW_Python

与C语言的指针相比,C++的应用在实现层面上保留了指针的高效,又在软件工程层面提高了程序的可读性和可维护性参考《Reference(引用) vs Pointer(指针) in C++》

第一步:创建引用。

#include<iostream>

using namespace std;

int main()
{
    int i = 100;
    int& r = i;  //引用在创建时,必须被初始化;一旦初始化就不能更改引用对象
    int* p = &i;  //指针在创建时,可以初始化,可以不初始化;可以更改指向的对象

    cout << "i is: " << i << ";" << "i's reference is: " << r << endl;
    r = r - 10;
    *p = *p - 10;
    i = i - 10;
    cout << "i is: " << i << ";" << "i's reference is: " << r << endl;

    return 0;
}

从反汇编语言中可以看到:

引用vs指针的初始化 引用vs指针的操作

第二步:用引用传参,其好处是:

#include<iostream>

using namespace std;
void swap(int a, int b)
{
    int tmp = b;
    b = a;
    a = tmp;
}
void swap_by_ref(int& a, int& b)
{
    int tmp = b;
    b = a;
    a = tmp;
}
void swap_by_pointer(int* a, int* b)
{
    int tmp = *b;
    *b = *a;
    *a = tmp;
}
int main()
{
    int a = 100;
    int b = 50;

    cout << "Initial value" << endl;
    cout << "a: " << a << ";" << "b: " << b << endl;
    
    cout << "excute the swap(a, b)" << endl;
    swap(a, b);
    cout << "a: " << a << ";" << "b: " << b << endl;

    cout << "excute the swap_by_ref(a, b)" << endl;
    swap_by_ref(a, b);
    cout << "a: " << a << ";" << "b: " << b << endl;

    cout << "excute the swap_by_pointer(&a, &b)" << endl;
    swap_by_pointer(&a, &b);
    cout << "a: " << a << ";" << "b: " << b << endl;

    return 0;
}
传形参不能实现对实参的修改
调用比较 汇编实现比较 引用vs指针实现比较
第三步:把引用作为函数返回值,注意不能引用局部变量,因为局部变量离开自己的作用域后,会被自动销毁。
完毕
上一篇下一篇

猜你喜欢

热点阅读