C++深度解析教程笔记6
- [第12课 - const常量&引用数组](#第12课 - const常量&引用数组)
本文学习自狄泰软件学院 唐佐林老师的 C++深度解析教程,图片全部来源于课程PPT,仅用于个人学习记录
第12课 - const常量&引用数组
实验-const常量的判别
cpp
#include <stdio.h>
int main()
{
const int x = 1;//在符号表,是常量
const int& rx = x;//rx是x的别名,对应为x分配的内存空间,rx是只读变量
int& nrx = const_cast<int&>(rx);//去除只读属性,目标类型只能是指针或者引用
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);
//可变的
volatile const int y = 2;//2没放符号表,放在内存里
int* p = const_cast<int*>(&y);//目标类型指针
*p = 6;//修改指针指向的值
printf("y = %d\n", y);//y改变了,证明了volatile修饰的变量放到了内存里
printf("p = %p\n", p);//y的地址
const int z = y;//z是只读变量
p = const_cast<int*>(&z);
*p = 7;
printf("z = %d\n", z);//变化了,说明了使用变量初始化的const常量是只读变量
printf("p = %p\n", p);
char c = 'c';
char& rc = c;
const int& trc = c;//const int & <--- char 类型不同的引用会生成新的只读变量,跟c毫无关系
rc = 'a';//更改引用 的值
printf("c = %c\n", c);
printf("rc = %c\n", rc);
printf("trc = %c\n", trc);
printf("&c = %p\n", &c);
printf("&rc = %p\n", &rc);
printf("&trc = %p\n", &trc);
return 0;
}
/*
x = 1
rx = 5
nrx = 5
&x = 0060FEE4
&rx = 0060FEE4
&nrx = 0060FEE4
y = 6
p = 0060FEE0
z = 7
p = 0060FEDC
c = a
rc = a
trc = c
&c = 0060FEDB
&rc = 0060FEDB
&trc = 0060FEE8
*/
实验-引用作为数组元素
c
#include <stdio.h>
int a = 1;
struct SV
{
int& x;
int& y;
int& z;
};
int main()
{
int b = 2;
int* pc = new int(3);
SV sv = {a, b, *pc};
int &array[]={a,b}; error: declaration of 'array' as array of references
//int& array[] = {a, b, *pc}; // &array[1] - &array[0] = ? Expected ==> 4
// error: declaration of 'array' as array of references
printf("&sv.x = %p\n", &sv.x);
printf("&sv.y = %p\n", &sv.y);
printf("&sv.z = %p\n", &sv.z);
//&sv.x = 0000000000403010
//&sv.y = 000000000061FE14
//&sv.z = 0000000000DA6E90
delete pc;
return 0;
}