(5)在工程項目開發中:
當進行c++編程時,直接站在使用的角度來看待引用,與指針毫無關系,引用就是變量的別名
當對C++代碼進行調試分析時,一些特殊情況,可以考慮站在C++編譯器的角度來看待引用
代碼實踐:
版本一:
#include <stdio.h>
int a = 2;
struct SV{
int& x;
int& y;
int& z;
};
int main()
{
int b =4;
int* pc = new int(3) ;
SV sv = {a,b,*pc};
printf("&sv.x = %p",&sv.x);
printf("&sv.y = %p",&sv.y);
printf("&sv.z = %p",&sv.z);
delete pc;
return 0;
}
輸出結果:
root@txp-virtual-machine:/home/txp# ./a.out
&sv.x = 0x601050
&sv.y = 0x7ffee11ba794
&sv.z = 0x1cfd010
版本二:
#include <stdio.h>
int a = 2;
struct SV{
int& x;
int& y;
int& z;
};
int main()
{
int b =4;
int* pc = new int(3) ;
SV sv = {a,b,*pc};
int& array[] = {a,b,*pc};//數組中的每個元素是引用就不可以;error: declaration of
‘array’ as array of references;C++ 天生要支持 C 語言,C
語言中數組中的每個元素在內存中是順序存放的,地址是遞增的,所以在 C++ 中也要兼容這個特性,而在 C++ 中唯有引用數組破快了這個特性,所以說
C++ 中不支持引用數組;&array[1] - &array[0] != Expected ==> 4
printf("&sv.x = %p",&sv.x);
printf("&sv.y = %p",&sv.y);
printf("&sv.z = %p",&sv.z);
delete pc;
return 0;
}
輸出結果:
root@txp-virtual-machine:/home/txp# g++ test.cpp
test.cpp: In function ‘int main()’:
test.cpp:16:14: error: declaration of ‘array’ as array of references
int& array[] = {a,b,*pc};
三、總結:
指針是一個變量
引用是一個變量的新名字
const引用能夠生成新的只讀變量
在編譯器內部使用指針常量實現"引用"
編譯時不能直接確定初始值的const標識符都是只讀變量