Posted on 2009-10-08 00:42
S.l.e!ep.¢% 阅读(197)
评论(0) 编辑 收藏 引用 所属分类:
C++
有这么一个关于虚函数和虚继承的问题,如下:
class A
{
char k[3];
public:
virtual void aa();
};
class B: public virtual A
{
char j[3];
public:
virtual void bb();
};
class C: public virtual B
{
char i[3];
public:
virtual void cc();
};
请问sizeof(A), sizeof(B), sizeof(C)分别为多少?
对于A, 我们很清楚的知道,其大小为8。
对于B,考虑到虚继承和自身的虚函数,我们也可以算出来起大小为8+8+4 = 20
对于C,其大小为20+8+4 = 32。
其中 4为虚继承所占用的指针。
这个看上去没有什么问题。但是当我把虚继承去掉以后,这里却有了一些变化?
首先,我猜想了一下,A是8,B是16,C是24。
可惜结果和我想的不一样,答案是8, 12, 16。很有规律的一个数字。
从A到B,只增加了4。什么原因呢?
在http://www.diybl.com/course/3_program/c++/cppjs/2007927/74925.html这里介绍了一些
The existence of virtual function(s)
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. That is
class Base {
public:
...
virtual void SomeFunction(...);
private:
int iAMem
};
class Derived : public Base
{
...
virtual void SomeOtherFunction(...);
private:
int iBMem
};
In the example above, sizeof(Base) will be 8 bytes--that is sizeof(int iAMem) + sizeof(vptr). sizeof(Derived) will be 12 bytes, that is sizeof(int iBMem) + sizeof(Derived). Notice that the existence of virtual functions in class Derived won't add anything more. Now Derived will set the vptr to its own virtual function table.
派生类和基类拥有相同的虚函数表。
但似乎虚继承的时候,又摈弃了这一做法。
所以两个是有所区别的。