标签:blog os io ar 2014 log sp on c
#include<iostream> using namespace std; class A { public: char ch[1]; virtual void fun() { } }; class B: virtual public A { public: char ch[1]; virtual void fun() { } }; class C: virtual public B { public: char ch[1]; virtual void fun() { } }; int main(void) { A a; B b; C c; int sizea = sizeof(a); //8 int sizeb = sizeof(b); //16 int sizec = sizeof(c); //24 return 0; }
因为虚继承增加了一个指向父类的虚函数指针。。。。所以空间增加了4
对于下面的继承,大小是32,
#include<iostream> using namespace std; class CommonBase { int co; }; class Base1: virtual public CommonBase { public: int b1; virtual void print1() { } }; class Base2: virtual public CommonBase { public: int b2; virtual void dump1() { } }; class Derived: public Base1, public Base2 { public: int d; void print2() { } void dump2() { } }; int main(void) { Derived d; int sized = sizeof(d); return 0; }
class Derived size(32): +--- | +--- (base class Base1) | | {vfptr} | | {vbptr} | | b1 | +--- | +--- (base class Base2) | | {vfptr} | | {vbptr} | | b2 | +--- | d +--- +--- (virtual base CommonBase) | co +---
#include<iostream> using namespace std; class A { public: char ch[1]; virtual void fun() { } }; class B: virtual public A { public: char ch[1]; virtual void fun() { } }; class C: virtual public A { public: char ch[1]; virtual void fun() { } }; class D: public B, public C { public: char ch[1]; virtual void fun() { } }; int main(void) { A a; B b; C c; D d; int sizea = sizeof(a); //8 int sizeb = sizeof(b); //16 int sizec = sizeof(c); //16 int sized = sizeof(d); //28 A的虚函数表4,B,C由于覆盖没有虚函数表;A的成员变量4(虚继承只出现一份),B,C的成员变量8,d数组4,B指向A的虚基表指针4,C指向A的虚基表指针4 return 0; }
#include<iostream> using namespace std; class A { public: char ch[1]; virtual void fun() { } }; class B: virtual public A { public: char ch[1]; virtual void fun() { } }; class C: virtual public A { public: char ch[1]; virtual void fun() { } }; class D: public B,virtual public C { public: char ch[1]; virtual void fun() { } }; int main(void) { A a; B b; C c; D d; int sizea = sizeof(a); //8 int sizeb = sizeof(b); //16 int sizec = sizeof(c); //16 int sized = sizeof(d); //28 return 0; }
#include<iostream> using namespace std; class A { public: char ch[1]; virtual void fun() { } }; class B: virtual public A { public: char ch[1]; virtual void fun() { } }; class C: virtual public A { public: char ch[1]; virtual void fun() { } }; class D: virtual public B,virtual public C { public: char ch[1]; virtual void fun() { } }; int main(void) { A a; B b; C c; D d; int sizea = sizeof(a); //8 int sizeb = sizeof(b); //16 int sizec = sizeof(c); //16 int sized = sizeof(d); //32 return 0; }
标签:blog os io ar 2014 log sp on c
原文地址:http://blog.csdn.net/taoqick/article/details/38977473