程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> C++類型轉換dynamic_cast解析

C++類型轉換dynamic_cast解析

編輯:關於C++

C++的類型轉換有四種 const_cast, reinterpret_cast, static_cast, dynamic cast

這邊舉一個dynamic cast的小例子


#include 

using namespace std;

class BaseClass{
    public :
    int m_iNum;

    virtual void foo() {}; //基類必須有虛函數。保持多態特性才能使用dynamic_cast
};

class DerivedClass : public BaseClass{
    public :
    char* m_szName;

    DerivedClass(char* str) {
        m_szName = new char[strlen(str) + 1];
        strcpy(m_szName, str);
    }

    ~DerivedClass(){
        if(m_szName != NULL){
            delete []m_szName;
            m_szName = NULL;
            
        }
    }
    void bar() {};
};

int main() {
    //64位系統, int:4, vtable_prt:8 輸出為16
    cout << "sizeof(BaseClass) = " << sizeof (BaseClass) << endl;
    //64位系統, 4 + 8 + 8 = 24
    cout << "sizeof(DerivedClass) = " << sizeof (DerivedClass) << endl;

    char *p = "abc";
    BaseClass *pb = new DerivedClass(p);
    cout << "sizeof(*pb): " << sizeof (*pb) << endl; // 16
    
    DerivedClass *pd1 = static_cast(pb); //子類->父類,靜態類型轉換,正確但不推薦
    DerivedClass *pd2 = dynamic_cast(pb); //子類->父類,動態類型轉換,正確

    cout << pd1->m_szName << endl; //abc
    cout << pd2->m_szName << endl; //abc

    cout << "sizeof(*pd1): " << sizeof (*pb) << endl; //16
    cout << "sizeof(*pd2): " << sizeof (*pb) << endl; //16

    BaseClass* pb2 = new BaseClass();
    DerivedClass *pd21 = static_cast(pb2); //父類->子類,靜態類型轉換,危險!訪問子類m_szName成員越界
    DerivedClass *pd22 = dynamic_cast(pb2); //父類->子類,動態類型轉換,安全的。結果是NULL

    cout << "sizeof(*pd21): " << sizeof (*pb) << endl; //16
    cout << "sizeof(*pd22): " << sizeof (*pb) << endl; //16
    
    cout << pd21 < m_szName則segmentation fault
    cout<< pd22 <
輸出結果為:

sizeof(BaseClass) = 16
sizeof(DerivedClass) = 24
sizeof(*pb): 16
abc
abc
sizeof(*pd1): 16
sizeof(*pd2): 16
0x7f9a7b403a60
0
sizeof(*pd21): 16
sizeof(*pd22): 16



  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved