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