
今天给大家分享一下这段时间学习c++的总结学习:c++里面的const关键字和引用。 一、const关键字的总结 1、const什么时候为只读变量,什么时候又是常量呢? (1)const常量的判别规则:
(2)const引用的类型与初始化变量的类型
代码版本一: #include <stdio.h>int main() { const int x = 1;//直接得到值,进入符号表,但是还是会为 x 分配空间,只不过这个空间 x 没有用而已 const int& rx = x;//rx代表只读变量,这个变量是编译器为x分配而没有使用的空间;引用代表变量的别名,而变量代表一段内存空间的别名,所以引用代表一段内存空间的别名 int& nrx = const_cast<int&>(rx); //消除 rx只读属性,和rx 代表的内存空间相同,同时c++里面的几种类型转换要掌握 nrx=5; printf("x = %d\n",x); printf("rx = %d\n",rx); printf("nrx = %d\n",nrx); printf("&x = %p\n",&x); printf("&rx = %p\n",&rx); printf("&nrx = %p\n",&nrx); return 0; } 输出结果: root@txp-virtual-machine:/home/txp# ./a.outx = 1 rx = 5 nrx = 5 &x = 0x7ffcc5fa8abc &rx = 0x7ffcc5fa8abc &nrx = 0x7ffcc5fa8abc 代码版本二: #include <stdio.h>int main() { volatile const int y = 2;// 只读变量,不会进入符号表 int *p = const_cast<int*>(&y);//y被 const修饰,取到的地址也有 const 属性,这里将地址只读属性去掉 *p = 8; printf("y = %d\n",y); printf("p = %p\n",p); return 0; } 输出结果: root@txp-virtual-machine:/home/txp# ./a.outy = 8 p = 0x7ffd78559684 代码版本三: #include <stdio.h>int main() { volatile const int y = 2; int *p = const_cast<int*>(&y); *p = 8; printf("y = %d\n",y); printf("p = %p\n",p); const int z = y ;//只读变量 p = const_cast<int*>(&z); *p= 9; printf("z = %d\n",z); printf("p = %p\n",p); return 0; } 输出结果: root@txp-virtual-machine:/home/txp# ./a.outy = 8 p = 0x7ffc5d651250 z = 9 p = 0x7ffc5d651254 代码版本四: #include <stdio.h>int main() { char c = 'c'; char& rc = c; const int& trc = c; // char 类型默认转换为 int;const 引用初始化类型不同,将得到新的只读变量,所以改变 rc 和 trc 没有丝毫关系,从我们的输出结果可以看出来 rc = 'a'; printf("c = %c\n",c); printf("rc = %c\n",rc); printf("trc = %c\n",trc); return 0; } 结果输出: root@txp-virtual-machine:/home/txp# ./a.outc = a rc = a trc = c 二、引用的总结: 1、引用与指针有什么关系,以及如何理解"引用的本质就是指针常量"? (1)指针是一个常量:
(2)引用只是一个变量的新名字:
(3)从使用c++语言的角度来看:
(4)从c++编译器的角度来看:
(5)在工程项目开发中:
代码实践: 版本一: #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\n",&sv.x); printf("&sv.y = %p\n",&sv.y); printf("&sv.z = %p\n",&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\n",&sv.x); printf("&sv.y = %p\n",&sv.y); printf("&sv.z = %p\n",&sv.z); delete pc; return 0; } 输出结果: root@txp-virtual-machine:/home/txp# g++ test.cpptest.cpp: In function ‘int main()’: test.cpp:16:14: error: declaration of ‘array’ as array of references int& array[] = {a,b,*pc}; 三、总结:
好了,今天的分享就到这里,如果文章中有错误或者不理解的地方,可以交流互动,一起进步。 |