先看代码:
#include <iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { const int a = 1; int *p = const_cast<int*>(&a); *p = 2; cout << "value a="<< a << endl; cout << "value *p=" <<*p << endl; cout << "address a=" <<&a << endl; cout << "address p=" <<p << endl; return 0; }
输出结果:
value a=1
value *p=2
address a=0022FBC8
address p=0022FBC8
请按任意键继续. . .
采用volatile关键字,修改为:
#include <iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { const volatile int a = 1; int *p = const_cast<int*>(&a); *p = 2; cout << "value a="<< a << endl; cout << "value *p=" <<*p << endl; cout << "address a=" <<&a << endl; cout << "address p=" <<p << endl; return 0; }
结果为:
value a=2
value *p=2
address a=1
address p=0042FDB8
请按任意键继续. . .
==============================================================================
本文转自被遗忘的博客园博客,原文链接:http://www.cnblogs.com/rollenholt/archive/2012/05/02/2478818.html,如需转载请自行联系原作者