C++类型转换运算符之const_cast<newtype>(expression)

功能:主要是在const和volatile之间的转换

Step1:const转换为volatile示例

//< Const_cast.cpp
#include <iostream>
using namespace std;

int main(int args, char* argv[])
{
	//< reference 
	const int &y = 0;
	int &ry = const_cast<int&>(y);
	cout<<y<<endl;
	cout<<ry<<endl;
	ry = 2;
	cout<<y<<endl;
	cout<<ry<<endl;

	//< pointer
	const char* a = "hello world.";
	char* b = const_cast<char*>(a);
	cout<<a<<endl;
	cout<<b<<endl;
	b = "GoodBye.";
	cout<<a<<endl;
	cout<<b<<endl;

	//< pointer
	int x = 100;
	const int* c = &x;
	int* d = const_cast<int*>(c);
	cout<<*c<<endl;
	cout<<*d<<endl;
	*d = 200;
	cout<<*c<<endl;
	cout<<*d<<endl;
	
	return 0;
}
运行结果为:



Step2:const_cast的重要用途是:调用别人家入参为non-const类型的接口,详见如下。

没用const_cast导致用const变量无法调用入参为non-const类型的接口,示例代码:

//< Const_cast.cpp
#include <iostream>
using namespace std;

void fun(int& x)
{
	cout<<x<<endl;
}

int main(int args, char* argv[])
{
	const int y = 0;
	fun(y);

	return 0;
}

这时候编译一定错误,const int&变量入参到fun(int&)时,入参类型不匹配,编译一定错误,错误信息如下:



用const_cast可以解决此问题,可以让y从const int类型去掉const后变成non-const的int&类型,就可以调用fun(int&)了。

只需修改main中的fun调用那行代码,修改为如下所示:

fun(const_cast<int&>(y))


经过以上修改,编译通过。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值