前言
我们说的虚表其实有很多种叫法:
· virtual method table(VMT)
· virtual function table(vftable)
· virtual call table
· dispatch table
· vtable
这些都是虚表的意思。虚表是一种利用程序语言实现的dynamic dispatch机制,或者说runtime method binding机制,也就是我们说的多态。
注:笔者在本文使用C++语言,并且统一用vTable来表示虚表。
虚函数
用virtual关键字修饰的函数就叫虚函数。
因为vTable(虚表)是C++利用runtime来实现多态的工具,所以我们需要借助virtual关键字将函数代码地址存入vTable来躲开静态编译期。这里我们先不深入探究,后面我会细说。
首先我们先来看一个没有虚函数,即没有用到vTable的例子:
#include <iostream> #include <ctime> using std::cout; using std::endl; struct Animal { void makeSound() { cout << "动物叫了" << endl; } }; struct Cow : public Animal { void makeSound() { cout << "牛叫了" << endl; } }; struct Pig : public Animal { void makeSound() { cout << "猪叫了" << endl; } }; struct Donkey : public Animal { void makeSound() { cout << "驴叫了" << endl; } }; int main(int argc, const char * argv[]) { srand((unsigned)time(0)); int count = 4; while (count --) { Animal *animal = nullptr; switch (rand() % 3) { case 0: animal = new Cow; break; case 1: animal = new Pig; break; case 2: animal = new Donkey; break; } animal->makeSound(); delete animal; } return 0; } |
程序中有一个基类Animal,它有一个makeSound()函数。有三个继承自Animal的子类,分别是牛、猪、驴,并且实现了自己的makeSound()方法。很简单的代码,是吧。
我们运行程序,你觉得输出结果会是什么呢?不错,这里会连续执行4次Animal的makeSound()方法,结果如下:
为什么?因为我们的基类Animal的makeSound()方法没有使用Virtual修饰,所以在静态编译时就makeSound()的实现就定死了。调用makeSound()方法时,编译器发现这是Animal指针,就会直接jump到makeSound()的代码段地址进行调用。
ok,那么我们把Animal的makeSound()改为虚函数,如下:
struct Animal {
virtual void makeSound()
{
cout << "动物叫了" << endl;
}
};
运行会是怎样?如你所料,多态已经成功实现:
接下来就是大家最关心的部分,这是怎么回事?编译器到底做了什么?
虚表
为了说明方便,我们需要修改一下基类Animal的代码,不改变其他子类,修改如下:
struct Animal { virtual void makeSound() { cout << "动物叫了" << endl; } virtual void walk() {} void sleep() {} }; struct Cow : public Animal { void makeSound() { cout << "牛叫了" << endl; } }; struct Pig : public Animal { void makeSound() { cout << "猪叫了" << endl; } }; struct Donkey : public Animal { void makeSound() { cout << "驴叫了" << endl; } }; |