有這么一個(gè)關(guān)于虛函數(shù)和虛繼承的問題,如下:
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();
};
請(qǐng)問sizeof(A), sizeof(B), sizeof(C)分別為多少?
對(duì)于A, 我們很清楚的知道,其大小為8。
對(duì)于B,考慮到虛繼承和自身的虛函數(shù),我們也可以算出來起大小為8+8+4 = 20
對(duì)于C,其大小為20+8+4 = 32。
其中 4為虛繼承所占用的指針。
這個(gè)看上去沒有什么問題。但是當(dāng)我把虛繼承去掉以后,這里卻有了一些變化?
首先,我猜想了一下,A是8,B是16,C是24。
可惜結(jié)果和我想的不一樣,答案是8, 12, 16。很有規(guī)律的一個(gè)數(shù)字。
從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.
派生類和基類擁有相同的虛函數(shù)表。
但似乎虛繼承的時(shí)候,又?jǐn)P棄了這一做法。
所以兩個(gè)是有所區(qū)別的。
posted on 2009-10-07 22:43
Sandy 閱讀(1963)
評(píng)論(2) 編輯 收藏 引用 所屬分類:
c++學(xué)習(xí)