1.1 系统内置类型
#include<iostream>
using namespace std;
int main()
{
const int test = 10;
int* p = const_cast<int*>(&test);
*p = 20;
cout << "test的地址为:" << &test << " test的值为:" << test << endl;;
cout << "p的地址为:" << p << " p的值为:" << *p;
system("pause");
return 0;
}
test的地址为:009AFA44 test的值为:10
p的地址为: 009AFA44 p的值为:20
1.2 用户自定义类型
int main(void)
{
struct TT
{
int a;
int b;
};
const TT s = {1,2};
cout << "[s]:" << s.a <<","<<s.b << endl; //输出 1,2
TT *result = const_cast<TT *>(&s);
result->a = 10;
result->b = 20;
cout << "[s]:" << s.a <<","<<s.b << endl;//输出 10,20
cout << "[r]:" << result->a <<","<<result->b << endl;//输出 10,20
getchar();
return 0;
}
[s]:1,2
[s]:10,20
[r]: 10,20
对于常量折叠这种编译器预处理,只对内置类型有效,对于自定义类型就没有效果。
1.3 问题
#include<iostream>
using namespace std;
int main()
{
int i = 10;
const int test = i;
int* p = const_cast<int*> (&test);
*p = 24;
cout << "i的地址是:" << &i << " i的值是:" << i << endl;
cout << "p的地址是:" << p << " p的值是:" << *p << endl;
cout << "test的地址是:" << &test << " test的值是:" << test<<endl;
}
i的地址是:003AF808 i的值是:10
p的地址是:003AF7FC p的值是:24
test的地址是:003AF7FC test的值是:24