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

版权声明:所有博客均由作者本人原创,若要转载,请注明出处。谢谢 https://blog.csdn.net/LU_Leo/article/details/82714745

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;
}

猜你喜欢

转载自blog.csdn.net/LU_Leo/article/details/82714745
今日推荐