C++中Vptr和Vtable的机制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19224126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mechanism of Vptr and Vtable in C++
提问by Blue Diamond
In C++, during dynamic binding, consider the following example...
在 C++ 中,在动态绑定期间,请考虑以下示例...
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.
由于声明了虚拟关键字/动态绑定,上述函数的输出为“Derived”。
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?
根据我的理解,将创建一个包含虚拟函数地址的虚拟表(Vtable)。在这种情况下,为派生类创建的虚拟表指向继承的 virtual fun()
。并且bptr->fun()
将得到解决bptr->vptr->fun();
。这指向继承的基类函数本身。我不是很清楚派生类函数是如何调用的?
回答by Santosh Sahu
Just went through this link virtual table and _vptr
刚刚通过这个链接虚拟表和_vptr
It says that the workflow will be like ..
它说工作流程将像..
base_ptr->base_vptr----> to check the access of virtual function in base class.
base_ptr->derived_vptr->virtual_function()---> to call/invoke the virtual function.
base_ptr->base_vptr----> 检查基类中虚函数的访问。
base_ptr->derived_vptr->virtual_function()---> 调用/调用虚函数。
Hence the derived class virtual function is called.. Hope you find it helpful.
因此派生类虚函数被称为..希望你觉得它有帮助。
回答by Kos
And bptr->fun() will be getting resolved to bptr->vptr->fun();. This points to the base class function itself.
并且 bptr->fun() 将被解析为 bptr->vptr->fun();。这指向基类函数本身。
Wrong. The Derived
instance's vptr (a hidden field in each instance) points to the Derived
vtable.
错误的。该Derived
实例的vptr的(每个实例中隐藏字段)指向Derived
虚函数表。
回答by John Dibling
The Standard doesn't specify the mechanism by which polymorphism is implemented. All the Standard says is how it should work -- not how compiler vendors should implement it.
该标准没有指定实现多态的机制。标准说的是它应该如何工作——而不是编译器供应商应该如何实现它。
That being said, you have it pretty much right as far as GCC under Linux and MSVC under Windows is concerned, and I would expect most other compilers to be similar.
话虽如此,就 Linux 下的 GCC 和 Windows 下的 MSVC 而言,您的看法非常正确,我希望大多数其他编译器也类似。