C++ 类型转换
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;//1、靜態類型轉換
void test01()
{//內置數據類型char a = 'a';//static_cast<目標類型>(原對象)double d = static_cast<double>(a);cout << d << endl;
}class Base
{virtual void func(){};
};
class Son :public Base
{virtual void func(){};
};
class Other
{};
void test02()
{//自定義數據類型Base * base = NULL;Son * son = NULL;//base 轉為 Son*類型 向下類型轉換 不安全Son * son2 = static_cast<Son *>(base);//son 轉為 Base * 類型 向上類型轉換 安全Base* base2 = static_cast<Base*>(son);//base 轉為 Other*//沒有父子關系的兩個類型之間是無法轉換成功的//Other * other = static_cast<Other *>(base);}//2、動態類型轉換
void test03()
{//內置數據類型 不允許內置數據類型之間的轉換//char c = 'c';//double d = dynamic_cast<double>(c);//自定義數據類型Base * base = NULL;Son * son = NULL;//base 轉為 Son* 類型 不安全 //不安全 轉換失敗//Son * son2 = dynamic_cast<Son*>(base);//son 轉為 Base* 安全Base * base2 = dynamic_cast<Base*>(son);//base 轉為Other* //Other* other = dynamic_cast<Other*>(base);//如果發生多態,那么父子之間的轉換 總是安全的Base * base3 = new Son;//將 base3轉為 Son*Son * son3 = dynamic_cast<Son*>(base3);}//3、常量轉換
void test04()
{//指針之間的轉換const int * p = NULL;//將 const int * 轉為 int *int * p2 = const_cast<int *>(p);//將 p2 轉為 const int * const int * p3 = const_cast<const int *>(p2);//引用之間的轉換const int a = 10;const int & aRef = a;int & aRef2 = const_cast<int &>(aRef);//不可以對非指針 或者 非引用 做const_cast轉換//int b = const_cast<int>(a);
}//4、重新解釋轉換 最不安全 不建議用
void tet05()
{//int a = 10;//int * p = reinterpret_cast<int*>(a);//將base* 轉為 Other * Base * base = NULL;Other * other = reinterpret_cast<Other *>(base);
}int main(){test01();system("pause");return EXIT_SUCCESS;
}
總結
- 上一篇: 飞利浦电视机24小时服务热线
- 下一篇: 中医如何治疗无精症