再论C++中的const和引用(三)
(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标识符都是只读变量