//此代碼在32位win下運行成功
#include<iostream>
using namespace std;
class A//A是空類,編譯器會用一個char類型標記這個類,大小為1
{
};
class B:public A//B繼承了A,但同樣也是空類,大小為1
{
};
class C:virtual public A//虛擬繼承的時候編譯器會安插一個指向父類的指針,大小為4
{
};
class D//大小為4
{
public:
int a;
static int b;//靜態變量被放在靜態存儲區
};
class E //print函數不占內存空間,大小為4
{
public:
void print(){cout<<"E"<<endl;}
private:
int a;
};
class F//虛函數會占用一個指針大小的內存,系統需要用這個指針維護虛函數表。大小為8
{
public:
virtual void print(){cout<<"F"<<endl;}
private:
int a;
};
class G:public F//多了一個虛函數內存大小不變,可見一個類只有一個虛函數指針。大小為8
{
public:
virtual void print(){cout<<"G"<<endl;}
virtual void print2(){cout<<"G2"<<endl;}
};
int main()
{
A a;
B b;
C c;
D d;
E e;
F f;
G g;
cout<<sizeof(A)<<" "<<sizeof(a)<<endl;//1 1
cout<<sizeof(B)<<" "<<sizeof(b)<<endl;//1 1
cout<<sizeof(C)<<" "<<sizeof(c)<<endl;//4 4
cout<<sizeof(D)<<" "<<sizeof(d)<<endl;//4 4
cout<<sizeof(E)<<" "<<sizeof(e)<<endl;//4 4
cout<<sizeof(F)<<" "<<sizeof(f)<<endl;// 8 8
cout<<sizeof(G)<<" "<<sizeof(g)<<endl;//8 8
return 0;
}