[c++]dynamic_pointer_cast用于shared_ptr之间类型的转换,基类需要有虚函数

Posted adream307

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[c++]dynamic_pointer_cast用于shared_ptr之间类型的转换,基类需要有虚函数相关的知识,希望对你有一定的参考价值。

//编译错误
#include <memory>
#include <iostream>

class base
 public:
    base()std::cout << "base" << std::endl;
    ~base()std::cout << "~base" << std::endl;
    void print()std::cout << "base::print" << std::endl;
;

class derived:public base
 public:
    derived()std::cout << "derived" << std::endl;
    ~derived()std::cout << "~derived" << std::endl;
    void print()std::cout << "derived::print" << std::endl;
;

int main()

    std::shared_ptr<base> b_ptr = std::make_shared<derived>();
    b_ptr->print();
    auto d_ptr = std::dynamic_pointer_cast<derived>(b_ptr);
    d_ptr->print();
    return 0;
//变异运行正常
#include <memory>
#include <iostream>

class base
 public:
    base()std::cout << "base" << std::endl;
    virtual ~base()std::cout << "~base" << std::endl;
    void print()std::cout << "base::print" << std::endl;
;

class derived:public base
 public:
    derived()std::cout << "derived" << std::endl;
    ~derived()std::cout << "~derived" << std::endl;
    void print()std::cout << "derived::print" << std::endl;
;

int main()

    std::shared_ptr<base> b_ptr = std::make_shared<derived>();
    b_ptr->print();
    auto d_ptr = std::dynamic_pointer_cast<derived>(b_ptr);
    d_ptr->print();
    return 0;

 

以上是关于[c++]dynamic_pointer_cast用于shared_ptr之间类型的转换,基类需要有虚函数的主要内容,如果未能解决你的问题,请参考以下文章

在dynamic_pointer_cast之后调用派生类的构造函数

移动智能指针两次与复制

学习C++有啥用途?

C++语法小记---标准库

C++之父的C++元宇宙

[C++]C++入门到入土篇 HelloWorld 解析 && C++入门