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

1.static_cast

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

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

2.dynamic_cast

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

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

3.const_cast

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

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

static_cast,const_cat,reinterpret_cast,dynamic_cast四种类型的转换的区别_第1张图片

4.reinterpret_cast

强制类型转换

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

 

你可能感兴趣的:(C++)