C ++:为什么struct \ class需要虚拟方法才能实现多态? [英] C++: Why does a struct\class need a virtual method in order to be polymorphic?
问题描述
以下此问题 ,我想知道为什么C ++中的struct \ class必须具有虚拟方法才能实现多态.
Following this question, I'm wondering why a struct\class in C++ has to have a virtual method in order to be polymorphic.
强制使用虚拟析构函数很有意义,但是如果根本没有析构函数,为什么必须强制使用虚拟方法?
Forcing a virtual destructor makes sense, but if there's no destructor at all, why is it mandatory to have a virtual method?
推荐答案
因为C ++中的多态对象的类型基本上是由指向其vtable的指针确定的,而vtable是虚拟函数的表.但是,仅在至少有一个虚拟方法的情况下才创建vtable.为什么?因为在C ++中,您永远不会得到您未明确要求的东西.他们称其为您不需要为不需要的东西付钱".不需要多态吗?您刚刚保存了一个vtable.
Because the type of a polymorphic object in C++ is, basically, determined from the pointer to its vtable, which is the table of virtual functions. The vtable is, however, only created if there's at least one virtual method. Why? Because in C++, you never get what you didn't explicitly ask for. They call it "you don't have to pay for something you don't need". Don't need polymorphism? You just saved a vtable.
这篇关于C ++:为什么struct \ class需要虚拟方法才能实现多态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!