首页 > 代码库 > C++类型转换dynamic_cast解析

C++类型转换dynamic_cast解析

C++的类型转换有四种 const_cast, reinterpret_cast, static_cast, dynamic cast

这边举一个dynamic cast的小例子


#include <iostream>

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<DerivedClass *>(pb); //子类->父类,静态类型转换,正确但不推荐
    DerivedClass *pd2 = dynamic_cast<DerivedClass *>(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<DerivedClass *>(pb2); //父类->子类,静态类型转换,危险!访问子类m_szName成员越界
    DerivedClass *pd22 = dynamic_cast<DerivedClass *>(pb2); //父类->子类,动态类型转换,安全的。结果是NULL

    cout << "sizeof(*pd21): " << sizeof (*pb) << endl; //16
    cout << "sizeof(*pd22): " << sizeof (*pb) << endl; //16
    
    cout << pd21 <<endl; //0x7f9a7b403a60
    //如果访问 pd21 -> m_szName则segmentation fault
    cout<< pd22 <<endl; //0 这里是NULL
    return 0;
}

输出结果为:

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



C++类型转换dynamic_cast解析