日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++ 类型转换

發布時間:2023/11/30 c/c++ 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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; }

總結

以上是生活随笔為你收集整理的C++ 类型转换的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。