C++虚表,你搞懂了吗?

发表于:2016-7-01 09:46

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:iosxxoo    来源:51Testing软件测试网采编

#
DoNet
分享:
  前言
  我们说的虚表其实有很多种叫法:
  · 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; } };
21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号