Vptr和Vtable在C ++中的机制 [英] Mechanism of Vptr and Vtable in C++

查看:607
本文介绍了Vptr和Vtable在C ++中的机制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,在动态绑定期间,请考虑以下示例...

  class Base 
{
virtual void fun()
{
cout<<Base;
}
};

class Derived:Base
{
void fun()
{
cout<<Derived;
}
};

int main()
{
Base * bptr;
派生d;
bptr =& d;
bptr-> fun();
}

上述函数的输出是Derived关键字/动态绑定。



根据我的理解,将创建一个虚拟表(Vtable),其中包含虚拟函数的地址。在这种情况下,为派生类创建的虚拟表指向继承的虚拟 fun()。和 bptr-> fun()将得到解决为 bptr-> vptr-> fun(); 。这指向继承的基类函数本身。我不完全清楚如何调用派生类函数。

解决方案

刚刚通过这个链接虚拟表和_vptr



它表示工作流将be like ..


  1. base_ptr-> base_vptr ---->检查基类中虚拟函数的访问。 / p>



  2. base_ptr-> derived_vptr-> virtual_function()--->

因此派生类的虚拟函数被调用。希望你觉得有帮助。


In C++, during dynamic binding, consider the following example...

class Base
{
  virtual void fun()
  {
     cout<<"Base";
  }      
};

class Derived : Base
{
   void fun()
   {
     cout<<"Derived";
   }
};

int main()
{
  Base *bptr;
  Derived d;
  bptr=&d;
  bptr->fun();
}

The output of the above function is "Derived" due to the declaration of virtual keyword/dynamic binding.

As per my understanding, a virtual table (Vtable) would be created which contains the address of the virtual functions. In this case the virtual table created for the derived class points to the inherited virtual fun(). And bptr->fun() will be getting resolved to bptr->vptr->fun();. This points to the inherited base class function itself. I am not completely clear on how the derived class function is called?

解决方案

Just went through this link virtual table and _vptr

It says that the workflow will be like ..

  1. base_ptr->base_vptr----> to check the access of virtual function in base class.

  2. base_ptr->derived_vptr->virtual_function()---> to call/invoke the virtual function.

Hence the derived class virtual function is called.. Hope you find it helpful.

这篇关于Vptr和Vtable在C ++中的机制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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