型別轉換(靜態轉換:static_cast)
阿新 • • 發佈:2021-08-24
靜態轉換
- 使用方式 static_cast< 目標型別>(原始資料)
- 可以進行基礎資料型別轉換
- 父與子型別轉換
- 沒有父子關係的自定義型別不可以轉換
1.普通型別
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; //靜態轉換 static_cast<要轉成的型別>(待轉變數); //基礎型別 void test01() { char a = 'a'; double d = static_cast<double>(a); cout<< typeid(d).name() << endl; } int main() { test01(); system("Pause"); return 0; }
結果:
2.父子關係
取地址*轉換
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; //靜態轉換 static_cast<目標型別>(原始物件); //1.基礎型別轉換 void test01() { char a = 'a'; double d = static_cast<double>(a); cout << typeid(d).name() << endl; } //2.父子之間轉換 class Base{}; class Child:public Base{}; class Other{}; void test02() { Base* base = NULL; Child* child = NULL; //把Base轉成Child 向下轉換 不安全 Child* c2 = static_cast<Child*>(base); //把Child轉成Base 向上轉型 安全 Base* b2 = static_cast<Base*>(child);//轉Other型別 Other* other = static_cast<Other*>(base); //error 型別轉換無效 因為它們沒有父子關係 } int main() { test02(); //test01(); system("Pause"); return 0; }
應用轉換
Animal ani_ref; Dog dog_ref; //繼承關係指標轉換 Animal& animal01 = ani_ref; Dog& dog01 = dog_ref; //子類指標轉成父類指標,安全 Animal& animal02 = static_cast<Animal&>(dog01); //父類指標轉成子類指標,不安全 Dog& dog02 = static_cast<Dog&>(animal01);