static_cast,const_cat,reinterpret_cast,dynamic_cast四种类型的转换的区别

1.static_cast

一般的内置类型转换或者具有继承关系的对象之间的转换

#include <iostream>
using namespace std;
class animal{};
class cat:public animal{};
class people {};
int main()
{
	int a = 97;
	char c = static_cast<char>(a);
	animal* ani1 = NULL;
	cat* cat1 = static_cast<cat*>(ani1);
	cat* cat2 = NULL;
	animal* ani2 = static_cast<animal*>(cat2);
	return 0;
}

2.dynamic_cast

通常在基类和派生类之间进行转换,在转换前会对对象进行安全检查(父类的指针可以指向子类,反之则不行)

animal* ani3 = NULL;
//cat* cat3 = dynamic_cast<cat*>(ani3);//编译器报错
cat* cat4 = NULL;
animal* ani4 = dynamic_cast<animal*>(cat4);

3.const_cast

用于指针,引用,或者对象指针(可以增加或者消除const特性)

	int a = 10;
	const int& b = a;
	int c = const_cast<int&>(b);
	c = 20;
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	cout << "c = " << c << endl;

4.reinterpret_cast

强制类型转换

#include <iostream>
using namespace std;
class animal{};
class cat:public animal{};
class people {};
int main()
{
	animal* ani1 = NULL;
	cat* cat1 = reinterpret_cast<cat*>(ani1);
	cat* cat2 = NULL;
	animal* ani2 = reinterpret_cast<animal*>(cat2);
	people* p;
	animal* ani3 = reinterpret_cast<animal*>(p);
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值