#include <iostream> #include <memory> struct Base { int a; virtual void f() const { std::cout << "I am base!\n";} virtual ~Base(){} }; struct Derived : Base { void d() { std::cout << "Derived:d()\n"; } void f() const override { std::cout << "I am derived!\n"; } ~Derived(){} }; int main(){ auto basePtr = std::make_shared<Base>(); std::cout << "Base pointer says: "; basePtr->f(); auto derivedPtr = std::make_shared<Derived>(); std::cout << "Derived pointer says: "; derivedPtr->f(); // 上行的轉換(派生類到基類的轉換) std::cout << "Derived pointer static_pointer_cast to Base says: "; std::static_pointer_cast<Base>(derivedPtr)->f(); // 直接轉型,不構造臨時 shared_ptr // 下行的轉換(基類到派生類的轉換) std::cout << "Base pointer static_cast to derived says: "; static_cast<Derived*>(basePtr.get())->d(); // 構造臨時 shared_ptr ,而後調用 operator-> // 下行的轉換(基類到派生類的轉換) std::cout << "Base pointer static_pointer_cast to derived says: "; std::static_pointer_cast<Derived>(basePtr)->d(); // 轉換成對象 // 下行的轉換(基類到派生類的轉換) Derived& derived = static_cast<Derived&>(*basePtr); std::cout << "Base pointer static_cast to derived Obeject says: "; derived.d(); // std::cout << "Base pointer dynamic_cast to derived says: "; // dynamic_cast<Derived*>(basePtr.get())->f(); //段錯誤 // Derived& derived1 = dynamic_cast<Derived&>(*basePtr); // derived1.d(); // 異常 // 下行的轉換(基類到派生類的轉換) auto downcastedPtr = std::dynamic_pointer_cast<Derived>(basePtr); if(downcastedPtr) { std::cout << "Base pointer dynamic_pointer_cast to derived says: "; downcastedPtr->d(); } // All pointers to derived share ownership std::cout << "Pointers to underlying derived: " << derivedPtr.use_count() << "\n"; }