在cpp中运行时多态的过程
Erstellt am: 2. September 2025
Erstellt am: 2. September 2025
在cpp中运行时多态的过程
在 C++ 中,运行时多态(Runtime Polymorphism)主要通过 虚函数(virtual function)+ 指针/引用 来实现。下面我会分几个步骤详细解释它的过程。
要产生运行时多态,需要满足以下条件:
virtual 关键字修饰)。实现运行时多态的核心机制就是 虚函数表(Virtual Table, V-Table):
举个例子:
cpp#include <iostream> using namespace std; class Base { public: virtual void show() { cout << "Base::show()" << endl; } }; class Derived : public Base { public: void show() override { cout << "Derived::show()" << endl; } }; int main() { Base* b = new Derived(); // 基类指针指向派生类对象 b->show(); // 调用的是 Derived::show() delete b; return 0; }
运行时步骤:
Base 类中声明了 virtual void show() → 编译器为其生成虚表。Derived 重写了 show(),它的虚表中的 show 指针指向 Derived::show()。Base* b = new Derived(); 时:
Derived 类的虚表。b->show() 时:
Base::show()。b 的 vptr → 定位到 Derived 的虚表 → 找到 Derived::show() → 调用它。Derived::show()。要不要我帮你画一张 虚函数表(V-Table)调用流程图,直观展示 Base* b = new Derived(); 时调用 b->show() 的内存指针跳转过程?