|
目錄
一、靜態轉換(static_cast)
- 用於類層次結構中基類(父類)和派生類(子類)之間指針或引用的轉換。
- 進行上行轉換(子轉父)是安全的;
- 進行下行轉換(父轉子)是不安全的。
- 用於基本數據類型之間的轉換,如把int轉換成char,把char轉換成int。
語法: static_cast<目標數據類型>(原變量/對象)
//內置數據類型
void test01()
{
char a = 'a';
double d = static_cast<double>(a);
cout << d << endl;
}
//對象轉換
class Base{};
class Son :public Base{};
class Other{};
void test02()
{
Base * base = NULL;
//base 轉爲 Son * 父轉子 向下類型轉換 不安全
Son * son = static_cast<Son *>(base);
// son 轉爲 Base* 子轉父 向上類型轉換 安全
Base * base1 = static_cast<Base*>(son);
//base1 轉 Other* 失敗
//Other * other = static_cast<Other*>(base1);
}
二、動態轉換(dynamic_cast)
- dynamic_cast主要用於類層次間的上行轉換和下行轉換,不允許內置數據類型轉換;
- 在類層次間進行上行轉換時,dynamic_cast和static_cast的效果是一樣的;
- 在進行下行轉換時,dynamic_cast具有類型檢查的功能,比static_cast更安全;
- 發生多態,轉換總是安全的
//2、動態類型轉換
void test03()
{
//不允許內置數據類型轉換
char a = 'a';
//double d = dynamic_cast<double>(a);
}
class Base1{ virtual void func1(){}; };
class Son1 :public Base1{ virtual void func1(){}; };
class Other1{};
void test04()
{
Base1 * base = NULL;
//base轉爲 Son1 * 父轉子 不安全
//Son1 * son = dynamic_cast<Son1 *>(base); //失敗 不安全
Son1 * son = NULL;
//son轉 Base1 * 子轉父 安全
Base1 * base1 = dynamic_cast<Base1*>(son);
//base1 轉Other1*
//Other1 * other = dynamic_cast<Other1*>(base1); 不可以 失敗
//如果發生多態,轉換總是安全的
Base1 * base1 = new Son1;
Son1 * son1 = dynamic_cast<Son1*>(base1);
}
三、常量轉換(const_cast)
該運算符用來修改類型的const屬性。
- 常量指針被轉化成非常量指針,並且仍然指向原來的對象;
- 常量引用被轉換成非常量引用,並且仍然指向原來的對象;
不可以對非指針或非引用進行轉換
//3、 const_cast常量轉換
void test05()
{
//指針
const int * p = NULL;
//p 轉爲 int *
int * pp = const_cast<int *>(p);
const int * ppp = const_cast<const int *>(pp);
//引用
int num = 10;
int &numref = num;
const int & numRef2 = const_cast<const int &>(numref);
int & numRef3 = const_cast<int&>(numRef2);
//不可以對非指針或非引用進行轉換
const int a = 10;
//int aa = const_cast<int>(a); 失敗
}
四、重新解釋轉換(reinterpret_cast)
這是最不安全的一種轉換機制,最有可能出問題。
主要用於將一種數據類型從一種類型轉換爲另一種類型。它可以將一個指針轉換成一個整數,也可以將一個整數轉換成一個指針.
基本不用