static_cast和dynamic_cast概述
動態類型轉換dynamic_cast概述
dynamic_cast<type> (expr)
: dynamic_cast 在運行時執行轉換,驗證轉換的有效性。如果轉換未執行,則轉換失敗,表達式 expr 被判定爲 null。dynamic_cast 執行動態轉換時,type 必須是類的指針、類的引用或者 void*,如果 type 是類指針類型,那麼 expr 也必須是一個指針,如果 type 是一個引用,那個 expr 也必須是一個引用。
靜態類型轉換static_cast概述
static_cast<type> (expr)
: static_cast 運算符執行非動態轉換,沒有運行時類檢查來保證轉換的安全性。例如,它可以用來把一個基類指針轉換爲派生類指針。
靜態類型轉換
//父子之間轉換
class Base{};
class Child :public Base{};
class Other{};
void test02()
{
Base * base = NULL;
Child * child = NULL;
//把base轉爲 Child*類型 向下 不安全
Child * child2 = static_cast<Child*>(base);
//把child 轉爲 Base* 向上 安全
Base * base2 = static_cast<Base*>(child);
//轉other類型 轉換無效
//Other * other = static_cast<Other*>(base);
}
動態類型轉換
基礎類型不可以轉換
void test03()
{
//基礎類型不可以轉換
char c = 'a';
//dynamic_cast非常嚴格,失去精度 或者不安全都不可以轉換
double d = dynamic_cast<double>(c);
}
動態類型轉換
如果發生了多態
class MyBase
{
virtual void func(){};
};
class MyChild :public MyBase
{
virtual void func(){};
};
class MyOther {};
void test05()
{
MyBase* base = NULL;
MyChild* child = NULL;
//child轉Base * 向上 安全
MyBase* base = dynamic_cast<MyBase*>(child);
//base 轉MyChild * 向下 不安全
//MyChild* child = dynamic_cast<MyChild*>(base);
//dynamic_cast 如果發生了多態,那麼可以讓基類轉爲派生類 ,向下轉換
MyBase* base = new MyChild;
MyChild* child = dynamic_cast<MyChild*>(base);
}
總結
不可以轉換基礎數據類型
父子之間轉換說明
父轉子 不可以
子轉父 可以
發生多態 都可以