C++:为什么结构类需要一个虚拟方法才能成为多态? [英] C++: Why does a structclass need a virtual method in order to be polymorphic?

查看:29
本文介绍了C++:为什么结构类需要一个虚拟方法才能成为多态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下这个问题,我想知道为什么 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.

这篇关于C++:为什么结构类需要一个虚拟方法才能成为多态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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