1. 程式人生 > 實用技巧 >C++引用本質的簡單理解

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; }