靜態(tài)轉(zhuǎn)換
格式:
static_cast<目標類型>(原始對象)
- 可以進行基礎(chǔ)數(shù)據(jù)類型轉(zhuǎn)換
- 父與子類型轉(zhuǎn)換
- 沒有父子關(guān)系的自定義類型不可以轉(zhuǎn)換
例:
class Base{};
class Child:public Base{};
class Other{};
void test()
{
Base *base=NULL;
Child* child=NULL;
//把base轉(zhuǎn)為Child*類型 向下轉(zhuǎn)型 不安全
Child*Child2=static_cast<Child*>(base);
//把child 轉(zhuǎn)為Base* 向上轉(zhuǎn)型 安全
Base*base2=static_cast<Base*>(child);
//無效轉(zhuǎn)換
//Other* other=static_cast<Other*>(base);
}
動態(tài)轉(zhuǎn)換
格式:
dynamic_cast<目標類型>(原類型)句葵;
- 基礎(chǔ)類型不可以轉(zhuǎn)換
- 非常嚴格,失去精度或者不安全都不可以轉(zhuǎn)換
父子之間可以轉(zhuǎn)換
- 父轉(zhuǎn)子不安全
- 子轉(zhuǎn)父安全
- 如果發(fā)生了多態(tài)割择,都可以轉(zhuǎn)換
class Base{
virtual void func() {};
};
class Child:public Base{
virtual void func() {};
};
class Other{};
void test()
{
Base* base = NULL;
Child* child = NULL;
//把base轉(zhuǎn)為Child*類型 向下轉(zhuǎn)型 不安全
//Child* Child2 = dynamic_cast<Child*>(base);
//把child 轉(zhuǎn)為Base* 向上轉(zhuǎn)型 安全
Base* base2 = dynamic_cast<Base*>(child);
Base* base3 = new Child;
Child* Child3 = dynamic_cast<Child*>(base3);
};
常量轉(zhuǎn)換
常量轉(zhuǎn)換(const_cast)
該運算符用來修改類型得const屬性
常量指針被轉(zhuǎn)化成非常量指針,并且仍然指向原來得對象
-
常量引用被轉(zhuǎn)換成非常量引用甩牺,并且仍然指向原來得對象
例:
//取出const
const int * p=NULL; int *newp=const_cast<int *>(p)
//加上const
int * p=NULL; const int *newp=const_cast<cosnt int *>(p)
//不能對非指針或非引用的變量進行轉(zhuǎn)換
//const int a=10; //int b=const<int>(a);錯誤
常量引用轉(zhuǎn)換成非常量引用
int num=10; int &refNum=num; const int &refNum2=const_cast<const int&>(refNum);
注意:不能直接對非指針和非引用得變量使用const_cast操作符去直接移除它的const
重新解釋轉(zhuǎn)換(reinterpret_cast)
不推薦使用赛惩,最不安全,最雞肋
int a=10;
int *p=reinterpret_cast<int*>(a);