C++简单菱形继承

版权声明:本文为博主原创文章,允许转载,转载请注明出处。 https://blog.csdn.net/KnightOnHourse/article/details/79959004
#include<iostream>
using namespace std;

//sizeof(A) = 4;
//sizoef(B) = 12(变量a,b共8字节,虚基类表指针4 )
//sizeof(C) = 12(变量a,c共8字节,虚基类表指针4 )

//sizeof(D) = 24(24,变量a,b,c,d共16,B的虚基类指针4,C的虚基类指针)


class A{public: int a;};
class B : virtual public A{public: int b;};
class C : virtual public A{public: int c;};
class D : public B, public C{public: int d;};

void main()
{
    D d; cout << "sizeof(D) = " << sizeof(D) << endl;
    d.a = 10; d.b = d.c = 20; d.d = 30;
    int* pInt = (int*)(&d);
    for(int i = 0; i < sizeof(D)/sizeof(int); i++){
        if(i == 0 || i == 2)
            cout << "[" << pInt << "] : " << *pInt << "(" << *((int*)(*pInt)) << ")" << endl;
        else
            cout << "[" << pInt << "] : " << *pInt << endl;
        pInt++;
    }
}


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页