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++智能指针类型转换的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23增量更新怎么做?-icode9专业技术文章分享
- 2024-11-23压缩包加密方案有哪些?-icode9专业技术文章分享
- 2024-11-23用shell怎么写一个开机时自动同步远程仓库的代码?-icode9专业技术文章分享
- 2024-11-23webman可以同步自己的仓库吗?-icode9专业技术文章分享
- 2024-11-23在 Webman 中怎么判断是否有某命令进程正在运行?-icode9专业技术文章分享
- 2024-11-23如何重置new Swiper?-icode9专业技术文章分享
- 2024-11-23oss直传有什么好处?-icode9专业技术文章分享
- 2024-11-23如何将oss直传封装成一个组件在其他页面调用时都可以使用?-icode9专业技术文章分享
- 2024-11-23怎么使用laravel 11在代码里获取路由列表?-icode9专业技术文章分享
- 2024-11-22怎么实现ansible playbook 备份代码中命名包含时间戳功能?-icode9专业技术文章分享