C++ 类型转换
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;//1、靜態(tài)類型轉(zhuǎn)換
void test01()
{//內(nèi)置數(shù)據(jù)類型char a = 'a';//static_cast<目標(biāo)類型>(原對(duì)象)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()
{//自定義數(shù)據(jù)類型Base * base = NULL;Son * son = NULL;//base 轉(zhuǎn)為 Son*類型 向下類型轉(zhuǎn)換 不安全Son * son2 = static_cast<Son *>(base);//son 轉(zhuǎn)為 Base * 類型 向上類型轉(zhuǎn)換 安全Base* base2 = static_cast<Base*>(son);//base 轉(zhuǎn)為 Other*//沒有父子關(guān)系的兩個(gè)類型之間是無法轉(zhuǎn)換成功的//Other * other = static_cast<Other *>(base);}//2、動(dòng)態(tài)類型轉(zhuǎn)換
void test03()
{//內(nèi)置數(shù)據(jù)類型 不允許內(nèi)置數(shù)據(jù)類型之間的轉(zhuǎn)換//char c = 'c';//double d = dynamic_cast<double>(c);//自定義數(shù)據(jù)類型Base * base = NULL;Son * son = NULL;//base 轉(zhuǎn)為 Son* 類型 不安全 //不安全 轉(zhuǎn)換失敗//Son * son2 = dynamic_cast<Son*>(base);//son 轉(zhuǎn)為 Base* 安全Base * base2 = dynamic_cast<Base*>(son);//base 轉(zhuǎn)為Other* //Other* other = dynamic_cast<Other*>(base);//如果發(fā)生多態(tài),那么父子之間的轉(zhuǎn)換 總是安全的Base * base3 = new Son;//將 base3轉(zhuǎn)為 Son*Son * son3 = dynamic_cast<Son*>(base3);}//3、常量轉(zhuǎn)換
void test04()
{//指針之間的轉(zhuǎn)換const int * p = NULL;//將 const int * 轉(zhuǎn)為 int *int * p2 = const_cast<int *>(p);//將 p2 轉(zhuǎn)為 const int * const int * p3 = const_cast<const int *>(p2);//引用之間的轉(zhuǎn)換const int a = 10;const int & aRef = a;int & aRef2 = const_cast<int &>(aRef);//不可以對(duì)非指針 或者 非引用 做const_cast轉(zhuǎn)換//int b = const_cast<int>(a);
}//4、重新解釋轉(zhuǎn)換 最不安全 不建議用
void tet05()
{//int a = 10;//int * p = reinterpret_cast<int*>(a);//將base* 轉(zhuǎn)為 Other * Base * base = NULL;Other * other = reinterpret_cast<Other *>(base);
}int main(){test01();system("pause");return EXIT_SUCCESS;
}
總結(jié)
- 上一篇: 飞利浦电视机24小时服务热线
- 下一篇: C++ 异常基本语法