简介:
C++中的const_cast运算符用于修改类型的const或volatile属性,从而强制消除对象的常量性。使用const_cast去除const限定的目的并不是为了修改它的内容。变量本身的const属性是不能去除的,要想修改变量的值,一般是去除指针(或引用)的const属性,再进行间接修改。
数据类型转换系列文章:
const_cast的使用:
调用形式:
const_cast<type_id> (exp)
通过const_cast运算符,也只能将const type*转换为type*,将const type&转换为type&。
也就是说源类型和目标类型除了const属性不同,其他地方完全相同。
例1: 一个简单的通过const*指针进行修改原值的例子:
#include <iostream>
using namespace std;
int main(void) {
int variable = 10;
int* const_p = &variable;
int* modifier = const_cast<int*>(const_p);
*modifier = 20;
cout << "variable:" << variable << endl; //输出:variable:20
return 0;
}
/*
编译环境:mac os下用g++编译:
*/
分析:
以上代码,通过modifier指针对variable进行了值的修改。
我们定义了一个非const的变量,但用带const限定的指针去指向它,在某一处我们突然又想修改了,可是我们手上只有指针,这时候我们可以用const_cast来修改了。
再看一个例子:
#include <iostream>
using namespace std;
void output(int* val)
{
cout << val<<endl;
}
int main(void)
{
const int i = 20;
const int *p = &i; //输出:0x7ffee92ff828
cout << p<<endl;
//output(p); //error: no matching function for call to 'output'
//note: candidate function not viable: 1st argument ('const int *') would lose const qualifier
output(const_cast<int *>(&i)); //输出:0x7ffee92ff828
return 0;
}
分析,定义了常量i,以及常量指针p,将p作为参数传递给output函数,结果编译失败;
使用const_cast后,,将i的地址去const后,传递给output函数,编译运行正常。
可见,const_cast的主要作用是去const。