0、總結
(1)要轉換的變量,轉換前、轉換后、轉換后的結果。
(2)一般情況下,避免進行類型轉換。
1、_static_cast(靜態類型轉換,int 轉換為char)
格式:TYPE B = static_cast<TYPE>(a)
reinterpreter_cast(重新解釋類型):專門用於指針類型的轉換。
void main() { double dpi = 3.1415; //int num1 = dpi;//默認自動類型轉換,會提示 warning int num2 = static_cast<int>(dpi);//靜態類型轉換,在編譯時會做類型檢查,如有錯誤會提示 // char* -> int* char* p1 = "hello"; int* p2 = nullptr; //p2 = static_cast<int*>(dpi);// 轉換類型無效, p2 = reinterpret_cast<int *>(p1);//相當於強制類型轉化,指針類型 cout << p1 << endl;//輸出字符串 cout << p2 << endl;//輸出指針的首地址 system("pause"); }
2、dynamic_cast(動態類型轉化,如子類和父類之間的多態類型轉換)
#include <iostream> using namespace std; class Animal { public: virtual void cry() = 0; }; class Dog :public Animal { public: virtual void cry() { cout << "wangwang" << endl; } void doHome() { cout << "kanjia" << endl; } }; class Cat :public Animal { public: virtual void cry() { cout << "miaomiao" << endl; } void doHome() { cout << "keai" << endl; } }; void playObj(Animal *base) { base->cry(); //運行時的類型識別, //父類對象轉換為子類對象 Dog *pDog = dynamic_cast<Dog*>(base);//如果不是該類型,則返回值為null if (pDog != NULL) { pDog->doHome(); } Cat *pCat = dynamic_cast<Cat*>(base);//如果不是該類型,則返回值為null if (pCat != NULL) { pCat->doHome(); } } void main() { Dog d1; Cat c1; //父類對象轉換為子類對象 playObj(&d1); playObj(&c1); //子類對象轉換為父類對象 Animal *pBase = nullptr; pBase = &d1; pBase = static_cast<Animal *>(&d1); system("pause"); }
3、const_cast(去 const 屬性)
該函數把只讀屬性去除。
p1 = const_cast<char*>(p);