虛函式的sizeof

2021-06-21 11:26:35 字數 1287 閱讀 7509

include

usingnamespacestd;

classbase1

virtualvoidfun11(){}

public:

virtual~base1();

};

classbase2

};

classderivedfromone:publicbase2

virtualvoidfun22(){}

};

classderivedfromtwo:publicbase1,publicbase2

};

voidmain()

輸出:

說明:

1)乙個類中若有虛函式,(不論是自己的虛函式,還是繼承而來的),那麼類中就有乙個成員變數:虛函式指標,這個指標指向乙個虛函式表,虛函式表的第一項是類的typeinfo資訊,之後的項為此類的所有虛函式的位址。

2)假設經過成員對齊後的類的大小為size個位元組。那麼類的sizeof大小可以這麼計算:size + 4*(虛函式指標的個數n)。**中,derivedfromtwo繼承自2個分支,所以有2個虛函式指標,所以sizeof大小為0 + 4* 2 = 8。

3)帶有虛函式的類的sizeof大小,實際上和虛函式的個數不相關,相關的是虛函式指標。

虛繼承和虛函式對sizeof的影響

先看例程 include include include include using namespace std class a const int size class a2 class b virtual public a class c public a class d public virt...

虛繼承和虛函式對sizeof的影響

先看例程 include include include include using namespace std class a const int size class a2 class b virtual public a class c public a class d public virt...

含有虛函式的類sizeof大小

01 include 02 using namespace std 04 class base1 06 virtual void fun11 07 public 08 virtual base1 09 11 class base2 13 15 class derivedfromone public ...