c++中dynamic_pointer_cast强制类型转换

#include <iostream>
#include <memory>

using namespace std;

class CBase
{
public:
    CBase() { }
    virtual ~CBase() { }

    void myBase()
    {
        cout << "CBase::myBase" << endl;
    }
};

class CDerive : public CBase
{
public:
    CDerive() { }
    ~CDerive() { }

    void myDerive()
    {
        cout << "CDerive::myDerive" << endl;
    }
};

int main(void)
{
    //上行的转换(派生类到基类的转换)
    shared_ptr<CDerive> spDeriveUp;
    shared_ptr<CBase> spBaseUp;
    spDeriveUp = make_shared<CDerive>();
    spBaseUp = dynamic_pointer_cast<CBase>(spDeriveUp);
    spBaseUp->myBase();

    //下行的转换(基类到派生类的转换)
    shared_ptr<CDerive> spDeriveDown;
    shared_ptr<CBase> spBaseDown;
    spBaseDown = make_shared<CBase>();
    spDeriveDown = dynamic_pointer_cast<CDerive>(spBaseDown);
    if (spDeriveDown == NULL)    //由于会进行类型的检查,这边是返回NULL
        cout << "spDeriveDown is null" << endl;

    /*
    shared_ptr<CDerive> spDeriveDown;
    shared_ptr<CBase> spBaseDown;
    spBaseDown = make_shared<CDerive>();
    spDeriveDown = dynamic_pointer_cast<CDerive>(spBaseDown);
    if (spDeriveDown == NULL)    //由于会进行类型的检查,这边是返回NULL
        cout << "spDeriveDown is null" << endl;
    spDeriveDown->myDerive();
    */

    return 0;

}

运行结果:

c++中dynamic_pointer_cast强制类型转换

#include <iostream>
#include <memory>

using namespace std;

class CBase
{
public:
    CBase() { }
    virtual ~CBase() { }

    void myBase()
    {
        cout << "CBase::myBase" << endl;
    }
};

class CDerive : public CBase
{
public:
    CDerive() { }
    ~CDerive() { }

    void myDerive()
    {
        cout << "CDerive::myDerive" << endl;
    }
};

int main(void)
{
    //上行的转换(派生类到基类的转换)
    shared_ptr<CDerive> spDeriveUp;
    shared_ptr<CBase> spBaseUp;
    spDeriveUp = make_shared<CDerive>();
    spBaseUp = dynamic_pointer_cast<CBase>(spDeriveUp);
    spBaseUp->myBase();

    //下行的转换(基类到派生类的转换)
    /*
    shared_ptr<CDerive> spDeriveDown;
    shared_ptr<CBase> spBaseDown;
    spBaseDown = make_shared<CBase>();
    spDeriveDown = dynamic_pointer_cast<CDerive>(spBaseDown);
    if (spDeriveDown == NULL)    //由于会进行类型的检查,这边是返回NULL
        cout << "spDeriveDown is null" << endl;
    */

    shared_ptr<CDerive> spDeriveDown;
    shared_ptr<CBase> spBaseDown;
    spBaseDown = make_shared<CDerive>();
    spDeriveDown = dynamic_pointer_cast<CDerive>(spBaseDown);
    if (spDeriveDown == NULL)    //由于会进行类型的检查,这边是返回NULL
        cout << "spDeriveDown is null" << endl;
    spDeriveDown->myDerive();    

    return 0;

}

运行结果:

c++中dynamic_pointer_cast强制类型转换

一些结论:

子类向基类转是一定没有问题的。基类转子类的话,必须基类的动态类型与要转换的子类一致
原文链接: https://www.cnblogs.com/z1141000271/p/15357024.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/214076

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 上午2:03
下一篇 2023年2月13日 上午2:04

相关推荐