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";
}