C++对象内存布局--⑩GCC编译器--虚拟继承--菱形继承

C++对象内存布局--⑩GCC编译器--虚拟继承--菱形继承

//GCC编译器--虚拟继承--菱形继承.cpp
//2010.8.19
//GCC编译器
#include <iostream>
using namespace std;

class Base
{
    public:
        Base(int a = 10):a(a)
        {
        }
        virtual void show()
        {
            cout << "Base::show()" << "\t" << a << endl;
        }
        virtual void testA()
        {
            cout << "Base::testA()" << "\t" << a << endl;
        }
    private:
        int a;
};

class BaseA : virtual public Base
{
    public:
        BaseA(int b = 20):b(b)
        {
        }
        virtual void showA()
        {
            cout << "BaseA::showA()" << "\t" << b << endl;
        }
        void testA()
        {
            cout << "BaseA::testA()" << "\t" << b << endl;
        }
    private:
        int b;
};

class BaseB : virtual public Base
{
    public:
        BaseB(int c = 30):c(c)
        {
        }
        virtual void showB()
        {
            cout << "BaseB::showB()" << "\t" << c << endl;
        }
    private:
        int c;
};

class Derived : public BaseA, public BaseB
{
    public:
        Derived(int d = 40):d(d)
        {
        }
        virtual void show()
        {
            cout << "Derived::show()" << "\t" << d << endl;
        }
        virtual void test()
        {
            cout << "Derived::test()" << "\t" << d << endl;
        }
    private:
        int d;
};

int main()
{
    Derived obj;
    int** p = (int**)&obj;
    cout << "Derived obj 内存布局:" << endl;
    for (int i = 0; i != sizeof(obj)/4; ++i)
    {
        cout << p[i] << endl;
    }
    cout << endl;
   typedef void (*fun)(void*pThis);//非常重要
	/*通过虚函数表调用函数*/
	/*第一个虚函数表指针。BaseA*/
	((fun)(p[0][0]))(p);
	((fun)(p[0][1]))(p);//头两个是BaseA的

	((fun)(p[0][2]))(p);
	((fun)(p[0][3]))(p);//后两个是Derived的
	/*第二个虚函数表指针。BaseB*/
	cout << endl;
	((fun)(p[2][0]))(p+2);
	/*第三个虚函数表指针。Base*/
    cout << endl;
	((fun)(p[5][0]))(p+5);
	((fun)(p[5][1]))(p+5);
    return 0;
}
/*
Derived obj 内存布局:
0x472d0c
0x14
0x472d28
0x1e
0x28
0x472d3c
0xa

BaseA::showA()  20
BaseA::testA()  20
Derived::show() 40
Derived::test() 40

BaseB::showB()  30

Derived::show() 40
BaseA::testA()  20
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值