Base类只是一个指针,所以Base大小是4个字节。
但Base类中添加一个int a,Base的大小变成8字节。
#include <iostream> #include <complex> using namespace std; class Base1 { public: Base1(){cout << "Base1" << endl;} ~Base1(){cout << "~Base1" << endl;} virtual void f(int){cout << "Base1 f(int)" << endl;} virtual void f(double){cout << "Base1 f(double)" << endl;} virtual void g(int i = 20){cout << "Base1 f(int)" << endl;} virtual void g2(int i = 10){cout << "Base1 f(int)" << endl;} }; class Base2 { public: Base2(){cout << "Base2" << endl;} ~Base2(){cout << "~Base2" << endl;} virtual void f(int){cout << "Base2 f(int)" << endl;} virtual void f(double){cout << "Base2 f(double)" << endl;} virtual void g(int i = 20){cout << "Base2 f(int)" << endl;} virtual void g2(int i = 10){cout << "Base2 f(int)" << endl;} /* 4 字节 */ int a; }; class Base3 { public: Base3(){ int a;int b;cout << "Base3" << endl;} ~Base3(){cout << "~Base3" << endl;} virtual void f(int){cout << "Base3 f(int)" << endl;} virtual void f(double){cout << "Base3 f(double)" << endl;} virtual void g(int i = 20){cout << "Base3 f(int)" << endl;} virtual void g2(int i = 10){cout << "Base3 f(int)" << endl;} /* 4 字节 */ int a; /* 4 字节 */ int b; }; int main() { Base1 a; /* 结果 4 字节 */ cout << sizeof(Base1) << endl; Base2 b; /* 结果 8 字节 */ cout << sizeof(Base2) << endl; Base3 c; /* 结果 12 字节 */ cout << sizeof(Base3) << endl; } /* [root@localhost test_class]# g++ class.cpp [root@localhost test_class]# ./a.out Base1 4 Base2 8 Base3 12 ~Base3 ~Base2 ~Base1 */