这个是 GPT 回答的,可以运行。

#include <iostream>
#include <memory>

class Base {
public:
    virtual void show() const {
        std::cout << "Base class" << std::endl;
    }
    virtual ~Base() = default; // 确保基类有虚析构函数
};

class Derived : public Base {
public:
    void show() const override {
        std::cout << "Derived class" << std::endl;
    }
};

#if false  // shared_ptr

int main() {
    // 创建一个 Derived 类的 shared_ptr
    std::shared_ptr<Derived> derivedPtr = std::make_shared<Derived>();

    // 上行转换:从派生类指针转换为基类指针
    std::shared_ptr<Base> basePtr = derivedPtr;
    basePtr->show(); // 输出 "Derived class"

    // 动态转换:从基类指针转换为派生类指针
    std::shared_ptr<Derived> derivedPtr2 = std::dynamic_pointer_cast<Derived>(basePtr);
    if (derivedPtr2) { // 如果转换成功
        derivedPtr2->show(); // 输出 "Derived class"
    }
    else {
        std::cout << "dynamic_pointer_cast 失败" << std::endl;
    }

    return 0;
}

#endif

#if true 

int main() {
    // 创建一个 Derived 类的 unique_ptr
    std::unique_ptr<Derived> derivedPtr = std::make_unique<Derived>();

    // 上行转换:从派生类指针转换为基类指针
    std::unique_ptr<Base> basePtr = std::move(derivedPtr);
    basePtr->show(); // 输出 "Derived class"

    // 自己新增测试 上面失去控制权之后,这里为 null,会进入 else
    // 不要使用失去控制权的指针对象   编译器一般也会有警告
    if (derivedPtr)  
        derivedPtr->show();
    else
        std::cout << "拾取控制权,为 null。" << std::endl;

    // 动态转换需要手动进行,因为 unique_ptr 不直接支持 dynamic_pointer_cast
    // 但可以通过 raw pointer 实现
    Derived* rawPtr = dynamic_cast<Derived*>(basePtr.get());
    if (rawPtr) {
        rawPtr->show(); // 输出 "Derived class"
    }
    else {
        std::cout << "dynamic_cast 失败" << std::endl;
    }

    return 0;
}

#endif
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.

输出:

Derived class
拾取控制权,为 null。
Derived class
  • 1.
  • 2.
  • 3.