static_cast 表示靜態變量的類型轉換, 如int->char, 不合適的類型轉換將會發生錯誤
/* static_cast 類型轉換 */ #include <iostream> using namespace std; int main() { int* pi = NULL; //char c = int(pi); //C++類型轉換 //char c = (int)pi; //C類型轉換 void* pc = pi; pi = static_cast<int *>(pc); char c = static_cast<int>(pi); //會出現報錯,因為int* 無法轉換為int類型 }
const_cast 表示const類型和非const類型的相互轉換
/* const_cast */ #include <iostream> using namespace std; int main() { //volatile表示易變的,可以變化的 const volatile int ci = 100; //表示數字是易變 int* pi = const_cast<int *>(&ci); //進行地址的賦值操作 *pi = 200; //對地址進行賦值 cout << *pi << endl; cout << ci << endl; cout << (void *)&ci << endl; cout << pi << endl; }
reinterpret_cast 表示進行隱式轉換
/* 進行隱式轉換 */ #include <iostream> using namespace std; int main(void) { //\000 = "\0" --> 0 char buf[] = "0001\00012345678\000123456"; struct Http { char type[5]; char id[9]; char passward[7]; }; Http *p_http = reinterpret_cast<Http*>(buf); cout << p_http->type << endl; cout << p_http->id << endl; cout << p_http->passward << endl; return 0; }