C++虚函数表的使用

虚函数表的意义

虚函数表是用于实现动态绑定的一种机制。

动态绑定

动态绑定用于确定该调用的函数,用于支持多态,如:

#include <iostream>

class B
{
public:
  virtual void bar();
  virtual void qux();
};

void B::bar()
{
  std::cout << "This is B's implementation of bar" << std::endl;
}

void B::qux()
{
  std::cout << "This is B's implementation of qux" << std::endl;
}

class C : public B
{
public:
  void bar() override;
};

void C::bar()
{
  std::cout << "This is C's implementation of bar" << std::endl;
}

B* b = new C();
b->bar();

类、虚函数指针以及虚函数表的关系

当类继承定义了虚函数的父类,则子类会继承虚函数表以及虚函数指针。

 -------
|class B|
 -------
 vpointer -----> Vtable of B
                bar -------------------
                qux --------------    |
                                 |    |
                                 |    |
                                 |  B::bar()
                                 |- B::qux() --- 
                                    C::bar()   |
 -------                                 |     |
|class C|                                |     |
 -------                                 |     |
 vpointer ----> Vtable of C              |     |
                bar  --------------------|     |
                qux  ---------------------------

参考

https://pabloariasal.github.io/2017/06/10/understanding-virtual-tables/

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值