#include <iostream>
using namespace std;
class A
{
public:
int a;
A()
{
printf("A::A()的this指针是%p\n", this);
}
void funA()
{
printf("A::funA()的this指针是%p\n", this);
}
};
class B
{
public:
int c;
B()
{
printf("B::B()的this指针是%p\n", this);
}
void funB()
{
printf("B::funB()的this指针是%p\n", this);
}
};
class C : public A, public B
{
public:
int c;
C()
{
printf("C::C()的this指针是%p\n", this);
}
void funC()
{
printf("C::funC()的this指针是%p\n", this);
}
};
int main(int, char**)
{
//this指针调整,多重继承
cout << sizeof(A) << endl;
cout << sizeof(B) << endl;
cout << sizeof(C) << endl;
C myc;//生成myc时,会构造C类的对象,类C继承A和B,在执行C的构造函数时,也会执行A和B的构造函数
myc.funA();
myc.funB();
myc.funC();
//编译结果
// 4
// 4
// 12
// A::A()的this指针是0x7fff6ada1a7c
// B::B()的this指针是0x7fff6ada1a80
// C::C()的this指针是0x7fff6ada1a7c
// A::funA()的this指针是0x7fff6ada1a7c
// B::funB()的this指针是0x7fff6ada1a80
// C::funC()的this指针是0x7fff6ada1a7c
// ==>
// 派生类对象包含基类子对象: myc是包含A类子对象,也包含B类子对象的.
// 如果派生类只从一个基类继承的话,这个派生类对象的地址和基类对象的地址相同
// 但如果一个派生类对象继承了多个基类:
// 第一个基类子对象的开始地址和派生类对象的开始地址相同.
// 而后续这些基类子对象的开始地址和派生类对象的开始地址相差多少呢?
// 前面基类子对象所占用的内存空间
return 1;
}
在C中添加一个B中相同的成员函数.
#include <iostream>
using namespace std;
class A
{
public:
int a;
A()
{
printf("A::A()的this指针是%p\n", this);
}
void funA()
{
printf("A::funA()的this指针是%p\n", this);
}
};
class B
{
public:
int c;
B()
{
printf("B::B()的this指针是%p\n", this);
}
void funB()
{
printf("B::funB()的this指针是%p\n", this);
}
};
class C : public A, public B
{
public:
int c;
C()
{
printf("C::C()的this指针是%p\n", this);
}
void funC()
{
printf("C::funC()的this指针是%p\n", this);
}
void funB()
{
printf("C::funB()的this指针是%p\n", this);
}
};
int main(int, char**)
{
//this指针调整,多重继承
cout << sizeof(A) << endl;
cout << sizeof(B) << endl;
cout << sizeof(C) << endl;
C myc;//生成myc时,会构造C类的对象,类C继承A和B,在执行C的构造函数时,也会执行A和B的构造函数
myc.funA();
myc.funB(); //已经被子类c覆盖了
myc.B::funB();
myc.funC();
//编译结果
// 4
// 4
// 12
// A::A()的this指针是0x7ffc217e244c
// B::B()的this指针是0x7ffc217e2450
// C::C()的this指针是0x7ffc217e244c
// A::funA()的this指针是0x7ffc217e244c
// C::funB()的this指针是0x7ffc217e244c
// B::funB()的this指针是0x7ffc217e2450
// C::funC()的this指针是0x7ffc217e244c
// ==>
// 总结:
//调用哪个子类的成员函数,this指针就会被编译器自动调整到内存布局中对应该子类对象的起始地址那去.
return 1;
}