C++智能指针类型转换

2022/5/5 12:42:43

本文主要是介绍C++智能指针类型转换,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

#include <iostream>
#include <memory>
 
struct Base 
{ 
    int a; 
    virtual void f() const { std::cout << "I am base!\n";}
    virtual ~Base(){}
};
 
struct Derived : Base
{
    void d()
    { std::cout << "Derived:d()\n"; }
    void f() const override
    { std::cout << "I am derived!\n"; }
    ~Derived(){}
};
 
int main(){
    auto basePtr = std::make_shared<Base>();
    std::cout << "Base pointer says: ";
    basePtr->f();
 
    auto derivedPtr = std::make_shared<Derived>();
    std::cout << "Derived pointer says: ";
    derivedPtr->f();
    
    
    // 上行的转换(派生类到基类的转换)
    std::cout << "Derived pointer static_pointer_cast to Base says: ";
    std::static_pointer_cast<Base>(derivedPtr)->f();


    // 直接转型,不构造临时 shared_ptr
    // 下行的转换(基类到派生类的转换)
    std::cout << "Base pointer static_cast to derived says: ";
    static_cast<Derived*>(basePtr.get())->d();

    // 构造临时 shared_ptr ,然后调用 operator->
    // 下行的转换(基类到派生类的转换)
    std::cout << "Base pointer static_pointer_cast to derived says: ";
    std::static_pointer_cast<Derived>(basePtr)->d();

    // 转换成对象
    // 下行的转换(基类到派生类的转换)
    Derived& derived = static_cast<Derived&>(*basePtr);
    std::cout << "Base pointer static_cast to derived Obeject says: ";
    derived.d();

    // std::cout << "Base pointer dynamic_cast to derived says: ";
    // dynamic_cast<Derived*>(basePtr.get())->f();  //段错误

    // Derived& derived1 = dynamic_cast<Derived&>(*basePtr);
    // derived1.d();       // 异常

    // 下行的转换(基类到派生类的转换)
    auto downcastedPtr = std::dynamic_pointer_cast<Derived>(basePtr);
    if(downcastedPtr)
    { 
        std::cout << "Base pointer dynamic_pointer_cast to derived says: ";
        downcastedPtr->d(); 
    }
 
    // All pointers to derived share ownership
    std::cout << "Pointers to underlying derived: " 
            << derivedPtr.use_count() 
            << "\n"; 
}


这篇关于C++智能指针类型转换的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程