C++中Vtable的意义是什么?

jeemy 2001-03-11 09:50:00
Vtable(虚函数表)那位大虾能解释一下!
...全文
606 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
joke100 2001-03-11
  • 打赏
  • 举报
回复
还是我来解释一把吧。
Vtable叫虚表。
每一个有虚函数的类都有这样一个东西。
它实际上记录了本类中所有虚函数的函数指针,也就是说是个函数指针数组的起始位置。

比如virtual void TheSecondFun()记录在数组的第二个元素,当一个该类的对象实例调用TheSecondFun时就根据对应关系把第二个函数指针取出来,再去执行该函数,这种行为叫晚绑定,也就是说在运行时才知道调用的函数是什么样子的,而不是在编译阶段就确定的早绑定。

lms 2001-03-11
  • 打赏
  • 举报
回复
主要是为了实现多态的

比如
class a
{
public:
virtual void fun1();
vitrual void fun2();

private:
int i;
}

class b : public a
{
public:
virtual void fun2();
virtual void fun3();
private:
int j;
}
则class a 的内存layout为(win32 platform)
begin of layout of class a
vtable pointer (pointer to vtable of class a see below) (4 bytes)
int i (4 bytes)
end of layout of class a

vtable of class a
begin of vtable of class a
start address of a::fun1 (4 bytes)
start address of a::fun2 (4 bytes)
end of vtable of class a

class b 的内存layout为(win32 platform)
begin of layout of class b
vtable pointer (pointer to vtable of class b see below) (4 bytes)
int i (4 bytes)
int j (4 bytes)
end of layout of class b

vtable of class b
begin of vtable of class b
start address of a::fun1 (4 bytes)
start address of b::fun2 (4 bytes)
start address of b::func3 (4 bytes)
end of vtable of class b

所以才有
a* p = new b;
p->fun2() 调 b::fun2()

70,037

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧