先看代码:
#includeusing namespace std;int _tmain(int argc, _TCHAR* argv[]){ const int a = 1; int *p = const_cast (&a); *p = 2; cout << "value a="<< a << endl; cout << "value *p=" <<*p << endl; cout << "address a=" <<&a << endl; cout << "address p=" < << endl; return 0;}
输出结果:
value a=1
value *p=2address a=0022FBC8address p=0022FBC8请按任意键继续. . .采用volatile关键字,修改为:
#includeusing namespace std;int _tmain(int argc, _TCHAR* argv[]){ const volatile int a = 1; int *p = const_cast (&a); *p = 2; cout << "value a="<< a << endl; cout << "value *p=" <<*p << endl; cout << "address a=" <<&a << endl; cout << "address p=" < << endl; return 0;}
结果为:
value a=2
value *p=2address a=1address p=0042FDB8请按任意键继续. . .