#include <iostream> using namespace std; class C {}; class A:public C { private: long a; long b; long c; public: A(long a,long b,long c){ this->a=a;this->b=b;this->c=c; } virtual void A_func(){}; // void A_func(); }; class B:public A{ private: long d; public: B(long a1,long a2,long a3,long a4):A(a1,a2,a3){ d=a4; } void B_func(); }; int main() { A x(1,2,3); B y(1,2,3,4); return 0; }
通过打印可知道
(gdb) p x $1 = (A) {<C> = {<No data fields>}, _vptr.A = 0x1004030d0 <vtable for A+16>, a = 1, b = 2, c = 3} (gdb) p y $2 = (B) {<A> = {<C> = {<No data fields>}, _vptr.A = 0x1004030f0 <vtable for B+16>, a = 1, b = 2, c = 3}, d = 4} (gdb) p sizeof(x) $3 = 32 (gdb) p sizeof(y) $4 = 40
当c为空的时候,c不占内存,看最底层的B类他继承了A类的大小,额外自己的成员变量极为40/8 =5个