C++基础#24:C++中的const_cast,数据类型转换

简介:

C++中的const_cast运算符用于修改类型的const或volatile属性,从而强制消除对象的常量性。使用const_cast去除const限定的目的并不是为了修改它的内容。变量本身的const属性是不能去除的,要想修改变量的值,一般是去除指针(或引用)的const属性,再进行间接修改。

数据类型转换系列文章:

C++中的动态强制dynamic_cast

C++中的RTTI机制之typeid

C++中的静态强制static_cast

C++中的reinterpret_cast数据类型转换

C++中的const_cast数据类型转换

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。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liranke

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值