初夏小談:C++中“指標”和“引用“”的區別
阿新 • • 發佈:2018-11-25
1.引用只能繫結一個實體,而指標可以指向不同實體
2.使用指標時要判空,而引用不需要因此更安全
3.引用在定義時必須初始化,指標不做要求
4.在sizeof中:引用結果是引用型別的大小,但指標始終是地址空間所佔位元組個數
void Size() { long long x = 10; long long& a = x; long long* p = &x; cout << sizeof(a) << endl; cout << sizeof(p) << endl; }
5.引用自加即引用的實體增加1,指標自加即指標向偏移一個型別的大小
void Add() { int num1 = 20; int& nu = num1; cout << num1 << endl; cout << &num1 << endl; cout << &nu << endl; nu++; cout << num1 << endl; cout << &num1 << endl; cout << &nu << endl; int num = 20; int* p = # cout << num << endl; cout << &num << endl; cout << &*p << endl; cout << &p << endl; p++; cout << num << endl; cout << &num << endl; cout << &*p << endl; cout << &p << endl; }
6.有多級指標,但沒有多級引用 // const int&& ra=10;(右值引用)C++11
7.訪問實體時,指標需要顯式解引用,而引用(編譯器處理)
8.沒有null引用,但有null指標若需要詳細程式碼請搜查看
https://github.com/AventadorSQ
珍&原始碼