C++智能指针类型转换

更新时间:2023-05-19 15:03:00 阅读: 评论: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
{jazz
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>();
moveup
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();
// 转换成对象
kemu
// 下⾏的转换(基类到派⽣类的转换)
Derived& derived = static_cast<Derived&>(*baPtr);
kaystd::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);
brine shrimp
// derived1.d();      // 异常
// 下⾏的转换(基类到派⽣类的转换)
auto downcastedPtr = std::dynamic_pointer_cast<Derived>(baPtr);
if(downcastedPtr)
{
2013年六级成绩查询
水的痕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-19 15:03:00,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/90/114687.html

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

标签:转换   基类   美国   类型转换
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图