一、栗子
#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!)
本文通过一个C++栗子详细解析了多重继承中子类对象的内存布局,以及this指针在调用基类成员函数时的行为。揭示了编译器如何调整this指针以正确调用不同基类的函数。
1613

被折叠的 条评论
为什么被折叠?



