對於下面的測試代碼(64位系統):C類繼承了A B 均爲虛類,所以在結果中sizeof(C) 結果爲32
#include<iostream>
using namespace std;class A
{
virtual void test()
{}
private:
int a;
};
class B
{
virtual void test()
{}
float b;
};
class C:public A ,public B
{
virtual void test()
{}
static double c; //靜態成員屬於類不屬於對象,所以sizeof(C) 時,不計算在內
};
struct A1
{
char a;
int b;
double c;
};
struct A2
{
int b;
double c;
char a;
};
int main()
{
C c;
cout<<"int = "<<sizeof(int)<<endl;
cout<<"int* = "<<sizeof(int*)<<endl;
cout<<sizeof(c)<<endl;
cout<<"A " <<sizeof(A)<<endl; //16
cout<<"B="<<sizeof(B)<<endl; //16
cout<<"-------------"<<endl;
cout<<sizeof(A1)<<endl;
cout<<sizeof(A2)<<endl;
}
tianxintong@txt:~/git/shujia/RB_tree$ ./tt
int = 4
int* = 8
32
A 16
B=16
-------------
16
24
分析: C 類繼承了A 類裏有一個虛表指針和一個int,字節對齊以後就是16個字節,B類中有一個float和一個虛表指針,爲16字節,而在C 類繼承了其基類的相應的虛表,並進行了修改(有虛函數的重寫則進行覆蓋,對每一個有相應虛函數的基類都進行覆蓋,這也是多態的原因,無虛函數的重寫則將派生類的虛函數添加到第一個基類的虛表的後面,這種沒有多態.)//