#include <iostream>
using namespace std;
class Base
{
public:
virtual void show() // 声明虚函数
{
cout << "Base" << endl;
}
};
class Derived : public Base
{
public:
void show() override // 覆盖虚函数
{
cout << "Derived" << endl;
}
};
int main()
{
Base *ptr = new Derived();
ptr->show(); // 运行时解析 Q:为什么会输出 Derived ?
delete ptr;
return 0;
}
这里,调用ptr->show()
时的具体步骤为:
-
从
ptr
所指对象的内存开始处读取vptr(虚指针)
。 -
使用
vptr(虚指针)
访问虚表。 -
在虚表中查找
show()
函数对应的条目(因为Derived类
覆盖了Base类
的show()
,所以虚表里的指针指向Derived::show()
)。 -
调用该地址对应的函数(即
Derived::show()
)。