派生类的大小 [英] Size of a derived class

查看:127
本文介绍了派生类的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello Guys,



请回答以下问题。



问题:A级有一个虚函数,B类有一个虚函数,C类有一个虚函数。



D类分别将A,B,C类作为私有,受保护,公共。



那么D级的大小是多少?



代码:

Hello Guys,

Please answer below query.

Question: a class A has one virtual function, class B has one virtual function, class C has one virtual function.

Class D derives class A, B , C as private, protected, public respectively.

Then what would be size of class D?

Code:

Class A
{
   public:
   virtual void fun1();
}

Class B
{  
   public:
   virtual void fun2();
}

Class C
{
   public:
   virtual void fun3();
}



Class D : private A, protected B, public C
{
   // There is not any virtual function of D class as A, B, C
}







1- D类的大小将以字节为单位。

2-如果在B类虚拟关键字被删除而所有其他东西都相同那么D级的大小是多少?





提前致谢。





问候,

Joy




1- What will be size of class D in bytes.
2- If in class B virtual keyword is removed and all other things are same then what would be size of class D?


Thanks in advance.


Regards,
Joy

推荐答案

取决于。



我认为v-table的大小是编译器的实现细节而不是规范(虽然我可能错了),这意味着编译器的大小可能不同。 />


也就是说,大多数可能都是用非常好的方式实现的milar方式,所以在你的例子中,我希望 D 的大小为 12 如果 B :: fun2 虚拟 8 否则。



这是32位版本,这些数字会在64位上加​​倍。



希望这会有所帮助,

Fredrik
It depends.

I think the size of the v-table is an implementation detail of the compiler rather than of the specification (I might be wrong, though) and that means that the size might differ across compilers.

That said, most are probably implemented in a very similar manner, so in your example I'd expect the size of D to be 12 if B::fun2 is virtual and 8 otherwise.

And that's on a 32 bit build, the figures would double on a 64 bit.

Hope this helps,
Fredrik


存在虚函数将在类中添加4个字节的虚拟表指针,这将添加到类的大小。同样,在这种情况下,如果类的基类已经直接或通过其基类具有虚函数,那么这个额外的虚函数将不会添加任何类的大小。虚拟表指针在类层次结构中是通用的。



1-



A类的_vptr = 4 字节

B类的_vptr = 4 字节

_Cptr的C类 = 4 字节



所以D类将 12 字节。



2 -



A类的_vptr = 4 字节

B类 = 1 字节,因为类不允许大小为0.这些函数与它无关。它只是一个虚拟字节

_cptr的C类 = 4 字节



所以D类将 9 字节。
Existence of virtual function(s) will add 4 bytes of virtual table pointer in the class, which will be added to size of class. Again, in this case, if the base class of the class already has virtual function(s) either directly or through its base class, then this additional virtual function won't add anything to the size of the class. Virtual table pointer will be common across the class hierarchy.

1-

_vptr of A class = 4 bytes
_vptr of B class = 4 bytes
_vptr of C class = 4 bytes

So Class D will be 12 bytes.

2 -

_vptr of A class = 4 bytes
B class = 1 byte, because it's not allowed for a class to be of size 0. The functions have nothing to do with it. It's just a dummy byte
_vptr of C class = 4 bytes

So Class D will be 9 bytes.


这篇关于派生类的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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