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

一、栗子

#include 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!)


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部