C++:为什么结构类需要一个虚拟方法才能成为多态?

2022-01-24 00:00:00 polymorphism c++ virtual-functions

以下这个问题,我想知道为什么 C++ 中的 structclass 必须有一个虚拟方法才能成为多态.

Following this question, I'm wondering why a structclass 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.

相关文章