C++新特性 强制转换const_cast

//C++新特性 强制转换const_cast
/*

	强制类型转换时具有一定风险的,有的转换并不一定安全,如果把整数数值转换成指针,把基类指针转换成派生指针
	把函数指针转换成另外一种函数指针,把常量指针转换成非常量指针等
	1.const_cast  只针对指针,引用,this  去除const属性
	2.static_cast
	3.reinterpret_cast
	4.dynamic_cast
*/
class CTest
{
public:
	CTest() :m_nTest(2){}
	void foo(int nTest) const
	{
		m_nTest = nTest;//错误,由于常成员函数,无法修改参数
		const_cast<CTest*> (this)->m_nTest = nTest;//这样可以修改
	}
public:
	int m_nTest;
};
int main()
{
	int n = 1;
	int * p = &n;//编译能过
	int * p = n; //编译报错,
	int * p1 = (int *)n; //编译能过,将地址为1的指针赋值,执行会奔溃

	//基类-->派生类  强转 会出错  强转隐患很多
	//规范转换


	const int n = 5;
	const std::string s = "hdm";
	//只针对指针,引用,this
	std::string t = const_cast<std::string>(s);//错误
	int k = const_cast<int>(n);//错误
	int * k = const_cast<int*> (&n);
	int& kRef = const_cast<int &>(n);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值