将创建多少个vptrs?

编程入门 行业动态 更新时间:2024-10-16 00:24:29
本文介绍了将创建多少个vptrs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我上课

I have class

class abc { public: int a; virtual void fun1(); }; class b: public abc { public: int b; virtual void fun2(); }; int main() { abc obj1,obj2,obj3; return 0; }

这里我为类abc创建了3个对象,所以这里将创建多少个vptrs?

here i created 3 objects for class abc, so here how many vptrs will be created?

推荐答案

Id取决于你如何计算它们。如果你指的是虚函数表的指针,重要的是要理解:每个类需要一个指针(下面我没有提到多重继承),但你必须在实例必须使用虚拟的地方有一个这样的指针的副本table,调用虚函数,使用后期绑定机制将调用分派给正确的实现。 但是唯一指针值的数量不超过类的数量。还要记住,你可以拥有许多没有vtable的课程。 另一方面,除非你不使用多重继承,否则这是真的(不是你的情况)虽然如此) 有些事情(很多人都不太了解)是当你输入某些类实例的某些运行时类型时编译时类型,在一般情况下,指针被移位,存在多重继承。发生这种情况是因为,在C ++中,vtables的片段组合为继承的结果。对于单继承,新方法只是附加到表中,但是具有多重继承,您必须将来自不相关源的vtable放在一起。这只是一个理解它的暗示。
-SA
Id depends how you count them. If you mean pointers to the virtual function table, it's important to understand: you need one pointer per class (without multiple inheritance I'll mention below), but you have to have a copy of such pointer everywhere the instance has to use the virtual table, which is needed to call virtual functions, to dispatch the call to right implementation, using the late binding mechanism. But the number of unique pointer values is no more than the number of classes. Remember also that you can have many classes not having vtable at all. From the other hand, this is true unless you don't use multiple inheritance (not your case though). One thing (poorly understood by many) is that when you type cast some runtime type of some class instance to some different compile-time type, the pointer is shifted, in general case, in presence of multiple inheritance. This happens because, in C++, the fragments of vtables combine as the result of inheritance. For single inheritance, new methods are just appended to the table, but with multiple inheritance, you have to put together vtables from unrelated sources. This is just a hint to understanding it.
—SA

我的赌注是没有 - 当没有可观察的程序输出时,为什么编译器会生成任何代码? My bet is none - why would the compiler generate any code when there's no observable output of the program?

更多推荐

将创建多少个vptrs?

本文发布于:2023-11-25 04:44:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628381.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多少个   vptrs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!