1. 程式人生 > >static_cast,const_cat,reinterpret_cast,dynamic_cast四種類型的轉換的區別

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