/*
第一章 C++语言简介
第二节 C++语言的特点
*三 、强制类型转换运算符
const_cast<类型名>(表达式)
【程序1-2】 输入/输出 示例
P35
*/
#include <iostream>
using namespace std;
int main() {
int a=10;
const int *p=&a; //不能使用常量指针p修改a的值
const int ca =30; //被const修饰
int *q;
cout<<"a的地址为:\t" <<&a<<"\ta的值为:\t"<<a<<endl;
cout<<"*p指向的地址为:" <<p<<"\t*p的值为:\t" <<*p<<endl;
q=const_cast<int *>(p); //去除p的常量性赋给q,如果写q=p;会报错
*q=20; //如果写*p=20;是错误的
cout<<"a的地址为:\t" <<&a<<"\ta的值为:\t"<<a<<endl;
cout<<"*p指向的地址为:" <<p<<"\t*p的值为:\t" <<*p<<endl;
cout<<"*q指向的地址为:"<<q<<"\t*q的值为:\t" <<*q<<endl;
cout<<"分界线"<<endl;
p=&ca; //ca的值不能修改
q=const_cast<int *>(p); //去除p的常量性赋给q,如果写q=p;会报错
*q=40; //*p=40;错误
cout<<"ca的地址为: \t" <<p<<"\tca的值为:\t"<<ca<<endl;
cout<<"*p指向的地址为:" <<p<<"\t*P的值为:\t"<<*p<<endl;
cout<<"*q指向的地址为:" <<q<<"\t*q的值为:\t"<<*q<<endl;
return 0;
}
/*
运行结果:
a的地址为: 0x6ffdfc a的值为: 10
*p指向的地址为:0x6ffdfc *p的值为: 10
a的地址为: 0x6ffdfc a的值为: 20
*p指向的地址为:0x6ffdfc *p的值为: 20
*q指向的地址为:0x6ffdfc *q的值为: 20
分界线
ca的地址为: 0x6ffdf8 ca的值为: 30
*p指向的地址为:0x6ffdf8 *P的值为: 40
*q指向的地址为:0x6ffdf8 *q的值为: 40
*/