- //此代码在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;
- }