const_cast转换符是用来移除变量的const或volatile限定符
const_cast就可以直接使用显示转换(int*)来代替:
#include<iostream>
using namespace std;
int main()
{
const int a = 1; //a的值永远不变
const int* t = &a; //t的值永远不变,但是*t可能改变
int* b = const_cast<int*>(t);//效果和int* b = (int*)(t)一样
*b = 2;
cout<<a<<"\t"<<*t<<"\t"<<*b<<endl;
cout<<&a<<"\t"<<t<<"\t"<<b<<endl;
}
--------------------------------------------------------------------------------
1 2 2
0xbfc96b1c 0xbfc96b1c 0xbfc96b1c
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
int main()
{
const int a = 1;
int c = 2;
const int* t = &a;
int* b = const_cast<int*>(t);
//*b = 2;
b = &c;
cout<<a<<"\t"<<*t<<"\t"<<*b<<endl;
cout<<&a<<"\t"<<t<<"\t"<<b<<endl;
}
--------------------------------------------------------------------------------
1 1 2
0xbfb46b5c 0xbfb46b5c 0xbfb46b58
--------------------------------------------------------------------------------
从这里我们可以很明显的看到其中的区别