cpp-類型轉換

C的類型轉換(type)變量 缺點不進行嚴格的類型判斷

c++類型轉換

1.static_cast 內置類型,具有繼承關係的類指針和引用

#include <iostream>
using namespace std;

class Animal{};
class Cat:public Animal{};

int main(){
	int a = 97;
	a = static_cast<char>(a);
	cout << a << endl;

	Animal *a1;
	a1 = static_cast<Cat*>(a1);

	Animal a2;
	Animal& a21 = a2;
	a21 = static_cast<Cat&>(a2);

	return 0;
}

2.dynamic_cast 子類轉父類

#include <iostream>
using namespace std;

class Animal{};
class Cat:public Animal{};

int main(){
	

	Cat *c1 = NULL;
	Animal *a1 = NULL;
	a1 = dynamic_cast<Animal*>(c1);

	Cat c2;
	Cat& c21 = c2;
	Animal a2;
	a2 = dynamic_cast<Animal&>(c21);

	return 0;
}

3.const_cast 增加/刪除類型const

#include <iostream>
using namespace std;

class Animal{};
class Cat:public Animal{};

int main(){
	

	const Cat *c1 = NULL;
	Cat *c11 = const_cast<Cat *>(c1);//刪除const

	c1 = const_cast<const Cat *>(c11);//增加const
	

	return 0;
}

4.reinterpret_cast 強制類型轉換

#include <iostream>
using namespace std;

class Animal{};
class Cat{};

typedef int(*FUNC2)();
typedef int(*FUNC1)();

int main(){
	
	Animal *a1 =NULL;
	Cat *c1 =NULL;
	c1 = reinterpret_cast<Cat*>(a1);

   //函數指針轉換
	FUNC2 f2 =NULL;
	FUNC1 f1 =NULL;
	f1 = reinterpret_cast<FUNC1>(f2);
	

	return 0;
}

請考慮轉換後的後果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章