1、std::static_pointer_cast():当指针是智能指针时候,向上转换,用static_cast 则转换不了,此时需要使用static_pointer_cast。 2、std::dynamic_pointer_cast():当指针是智能指针时候,向下转换,用dynamic_cast 则转换不了,此时需要使用dynamic_pointer_cast(此处注意:base基类需要至少有一个virtual成员函数(即多态类...
一、static_cast和dynamic_cast区别: 1、static_cast:向上转换,例如:基类向派生类转换 2、dynamic_cast:向下转换,例如:派生类向基类转换 二、static_poonter_cast和dynamic_pointer_cast区别同上,不过这两个只适用于智能指针
std::shared_ptr<T> static_pointer_cast( std::shared_ptr<U>&& r ) noexcept; (2) (C++20 起) template< class T, class U >std::shared_ptr<T> dynamic_pointer_cast( const std::shared_ptr<U>& r ) noexcept; (3) (C++11 起) template< class T, class U >std::shared_ptr<T> ...
If pb points to an object of type B and not to the complete D class, then dynamic_cast will know enough to return zero. However,static_castrelies on the programmer’s assertion that pb points to an object of type D and simply returns a pointer to that supposed D object. 即dynamic_cas...
调用右值重载(2,4,6,8)后,r为空且r.get()==nullptr,但对于dynamic_pointer_cast(4),若dynamic_cast失败则不修改r。 (C++20 起) 参数 r-要转换的指针 注解 表达式std::shared_ptr<T>(static_cast<T*>(r.get()))、std::shared_ptr<T>(dynamic_cast<T*>(r.get()))及std::shared_ptr<T>(con...
在进行下行转换时,dynamic_cast具有类型检查的功能,比static_cast更安全。 class B{ public: int m_iNum; virtual void foo(); }; class D:public B{ public: char *m_szName[100]; }; void func(B *pb){ D *pd1 = static_cast(pb);
If pb points to an object of type B and not to the complete D class, then dynamic_cast will know enough to return zero. However,static_castrelies on the programmer’s assertion that pb points to an object of type D and simply returns a pointer to that supposed D object. ...
在类层次间进行上行转换时,dynamic_cast和static_cast的效果是一样的; 在进行下行转换时,dynamic_cast具有类型检查的功能,比static_cast更安全。 class B{ public: int m_iNum; virtual void foo(); }; class D:public B{ public: char *m_szName[100]; ...
输出结果是:Null pointer on second type-cast 两个dynamic_cast都是下行转换,第一个转换是安全的,因为指向对象的本质是子类,转换的结果使子类指针指向子类,天经地义;第二个转换是不安全的,因为指向对象的本质是父类,“指鹿为马”或指向不存在的空间很可能发生!
常见四种显示转换方式如下所示,且先从功能强弱上排个序,从强到弱应该是:reinterpret_cast,旧式转换,static_cast,dynamic_cast。 (1)static_cast 用法:static_cast < type-id > ( exdivssion ) 该运算符把exdivssion转换为type-id类型,但没有运行时类型检查来保证转换的安全性。它主要有如下几种用法: ...