C++对象模型探索 / 子类的内存布局

一、栗子

#include <iostream>

class Father
{
public:
    Father()
    {
        std::cout << "I am father,this is " << this << std::endl;
    }

public:
    void func_father()
    {
        std::cout << "传入 Fahter::func_father() 的 this 指针是 " << this << std::endl;
    }
private:
    int father;
};

class Mother
{
public:
    Mother()
    {
        std::cout << "I am Mother,this is " << this << std::endl;
    }

public:
    void func_mother()
    {
        std::cout << "传入 Mother::func_mother() 的 this 指针是 " << this << std::endl;
    }
private:
    int mother;
};

class Son : public Father,
            public Mother
{
public:
    Son()
    {
        std::cout << "I am Son,this is " << this << std::endl;
    }

public:
    void func_Son()
    {
        std::cout << "传入 Son::func_Son() 的 this 指针是 " << this << std::endl;
    }
private:
    int son;
};

int main()
{
    Son s;

    std::cout << std::endl;
    
    s.func_father();
    s.func_mother();
    s.func_Son();

    return 0;
}

结果:

I am father,this is 0xffffcc14
I am Mother,this is 0xffffcc18
I am Son,this is 0xffffcc14

传入 Fahter::func_father() 的 this 指针是 0xffffcc14
传入 Mother::func_mother() 的 this 指针是 0xffffcc18
传入 Son::func_Son() 的 this 指针是 0xffffcc14

二、详解

        由上述代码可知,子类的内存布局如下图所示, 

        由于“Son”继承顺序是“Father”、“Mother”,所以内存布局中 Father 类排布在起始位置,之后是 Mother 类,最后才是 Son 类自身的变量(当然,初始化顺序也是 Father 、Mother,最后才是 Son )。

        具体为什么内存布局中只有变量而没有函数的原因,请看链接。 

        最后还有一个问题,为什么 Son 的对象调用可以调用 Father 和 Mother 类的函数呢?因为编译器在调用 Father 和 Mother 的函数时,调整了传入到 Func_Father 和 Func_Mother 函数的 this 指针,使 this 指针是各个函数所在类的对象的 this 指针,从而达到了调用各个类的函数的目的。

 

(SAW:Game Over!)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值