C++智能指针类型转换

更新时间:2023-05-14 19:12:40 阅读: 评论:0

C++智能指针类型转换#include <iostream>
#include <memory>
struct Ba
{
int a;
virtual void f() const { std::cout << "I am ba!\n";}
virtual ~Ba(){}
};
struct Derived : Ba
{
void d()
{ std::cout << "Derived:d()\n"; }
void f() const override
{ std::cout << "I am derived!\n"; }
~Derived(){}
千仞是什么意思};
int main(){
auto baPtr = std::make_shared<Ba>();
std::cout << "Ba pointer says: ";
baPtr->f();
auto derivedPtr = std::make_shared<Derived>();周杰伦经典歌词
政治的英文
std::cout << "Derived pointer says: ";
derivedPtr->f();
// 上⾏的转换(派⽣类到基类的转换)
std::cout << "Derived pointer static_pointer_cast to Ba says: ";
std::static_pointer_cast<Ba>(derivedPtr)->f();
// 直接转型,不构造临时 shared_ptr
// 下⾏的转换(基类到派⽣类的转换)
std::cout << "Ba pointer static_cast to derived says: ";
static_cast<Derived*>(())->d();
// 构造临时 shared_ptr ,然后调⽤ operator->
// 下⾏的转换(基类到派⽣类的转换)
std::cout << "Ba pointer static_pointer_cast to derived says: ";
std::static_pointer_cast<Derived>(baPtr)->d();
// 转换成对象
// 下⾏的转换(基类到派⽣类的转换)
Derived& derived = static_cast<Derived&>(*baPtr);
std::cout << "Ba pointer static_cast to derived Obeject says: ";
derived.d();
// std::cout << "Ba pointer dynamic_cast to derived says: ";
红松子// dynamic_cast<Derived*>(())->f();  //段错误会计管理
// Derived& derived1 = dynamic_cast<Derived&>(*baPtr);
膝关节疼痛的原因和治疗方法
// derived1.d();      // 异常
青春与爱情// 下⾏的转换(基类到派⽣类的转换)
电脑服务怎么打开auto downcastedPtr = std::dynamic_pointer_cast<Derived>(baPtr);
if(downcastedPtr)
{
std::cout << "Ba pointer dynamic_pointer_cast to derived says: ";
downcastedPtr->d();
}
// All pointers to derived share ownership
std::cout << "Pointers to underlying derived: "
<< derivedPtr.u_count()
<< "\n";
}

本文发布于:2023-05-14 19:12:40,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/89/897869.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:原因   转换   基类   疼痛   治疗   类型转换   电脑   经典
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图