#include <iostream>
using namespace std;
#pragma pack(2)
class A{
int i; //4
union U{ //14
char buff[13];
int i;
}u; //注意,这里是申明了一个union变量
enum{red, green, blue} color; //4
void foo() {} //0
typedef char* (*f)(void*); //0
int g(){int i;} //0
};
class B{
B(){} //0
virtual g(){} //4
virtual f(){} //所有虚函数放在一张虚表中,指向虚表的指针的4字节
};
class C{};
int main(){
cout<<sizeof(A)<<endl; //8
cout<<sizeof(B)<<endl; //4
cout<<sizeof(C)<<endl; //1
return 0;
}
再看一个:
#include <iostream>
using namespace std;
class A {
public:
int b;
char c; //注意地址对齐
virtual void print(){
cout<<"this is father's function!"<<endl;
}
};
class B : A {
public:
virtual void print(){
cout<<"this is children's function!"<<endl;
}
};
int main(void){
cout<<sizeof(A)<<","<<sizeof(A)<<endl; //12,12
return 0;
}