C++引用本质的简单理解

C++中的引用类型其本质就是指针常量,当我们使用引用时,编译器将会自动为我们定义一个定义指针常量并将被取别名的变量的地址赋值给该指针常量或者通过解引用指针常量来访问被取别名的变量

点击这里了解const和指针的结合使用

#include<iostream>

using namespace std;

/**
 * C++中引用的本质
 * essence n.本质;精华
 * convert sth to 把...转化成
 * statement n.声明;语句;陈述;报表
 */
int main() {
    int a = 20;
    //when the complier encounters the statement "int & ref = a", the complier will automatically convert it to statement "int * const ref = &a;",
    //and the essence of the reference type variable "ref" in C++ is a pointer constant
    int &ref = a;
    cout << "ref = " << ref << endl;

    //when the complier encounters the statement "ref = 40", the complier will automatically convert it to statement "*ref = 40;"
    ref = 40;
    cout << "a = " << a << endl;
    system("pause");

    return 0;
}

 

posted @ 2020-08-08 11:47  DNoSay  阅读(368)  评论(0编辑  收藏  举报