为什么需要虚拟表? [英] Why do we need virtual table?

查看:88
本文介绍了为什么需要虚拟表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找有关虚拟表的信息,但找不到任何易于理解的信息。

有人可以给我提供很好的示例(请从Wiki中获取),并提供解释或链接。 ?

I was looking for some information about virtual table, but can't find anything that is easy to understand.
Can somebody give me good examples(not from Wiki, please) with explanations, or links?

推荐答案

没有虚拟表,您将无法使运行时多态性起作用,因为所有对函数的引用都将在编译时绑定时间。一个简单的例子

Without virtual tables you wouldn't be able to make runtime polymorphism work since all references to functions would be bound at compile time. A simple example

struct Base {
  virtual void f() { }
};

struct Derived : public Base {
  virtual void f() { }
};

void callF( Base *o ) {
  o->f();
}

int main() {
  Derived d;
  callF( &d );
}

在函数 callF ,您只知道 o 指向 Base 对象。但是,在运行时,代码应调用 Derived :: f (因为 Base :: f 是虚拟的)。在编译时,编译器无法知道 o-> f()调用将执行的代码,因为它不知道 o 指向。

Inside the function callF, you only know that o points to a Base object. However, at runtime, the code should call Derived::f (since Base::f is virtual). At compile time, the compiler can't know which code is going to be executed by the o->f() call since it doesn't know what o points to.

因此,您需要一个称为虚拟表的东西,它实际上是一个函数指针表。每个具有虚拟功能的对象都有一个 v表指针,该指针指向该类型对象的虚拟表。

Hence, you need something called a "virtual table" which is basically a table of function pointers. Each object that has virtual functions has a "v-table pointer" that points to the virtual table for objects of its type.

callF 函数只需要在虚拟表中查找 Base :: f 的条目(它基于v-表指针),然后调用表条目指向的函数。可能 Base :: f ,但也可能指向其他内容- Derived :: f <例如,/ code>。

The code in the callF function above then only needs to look up the entry for Base::f in the virtual table (which it finds based on the v-table pointer in the object), and then it calls the function that table entry points to. That might be Base::f but it is also possible that it points to something else - Derived::f, for instance.

这意味着由于有了虚拟表,您可以在运行时具有多态性,因为实际调用的函数是在运行时确定,方法是在虚拟表中查找函数指针,然后通过该指针调用该函数-而不是直接调用该函数(非虚拟函数就是这种情况)。

This means that due to the virtual table, you're able to have polymorphism at runtime because the actual function being called is determined at runtime by looking up a function pointer in the virtual table and then calling the function via that pointer - instead of calling the function directly (as is the case for non-virtual functions).

这篇关于为什么需要虚拟表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆