源程序:
#include <iostream>
using namespace std;
int main()
{
int a = 10;
const int *p = &a;
const int ca = 30;
int *q;
cout << "a的地址为: " << &a << " a的值为: " << a << endl;
cout << "*p指向的地址为:" << p << " *p的值为: " << *p << endl;
q = const_cast<int *>(p); //去除p的常量性赋给q, 如果写p=q,则会报错
*q = 20;
cout << "a的地址为: " << &a << " a的值为: " << a << endl;
cout << "*p指向的地址为: " << p<< " *p的值为: " << *p << endl;
cout << "*q指向的地址为: " << q << " *p的值为: " << *q << endl;
cout << "分界线" << endl;
p = &ca; //ca的值不能修改
q = const_cast<int *>(p); //去除p的常量性赋给q
*q = 40;
cout << "ca的地址为: " << &ca << " ca的值为: " << ca << endl;
cout << "*p指向的地址为: " << p << " *p的值为: " << *p << endl;
cout << "*q指向的地址为: " << q << " *p的值为: " << *q << endl;
system("pause");
return 0;
}
运行结果: