一.同时继承多个基类
先看一段代码:
#include <iostream>
using namespace std;
class A {
public:
int a;
A()
{
printf("A::A()的this指针是:%p!\n", this);
}
void funcA()
{
printf("A::funcA()的this指针是:%p!\n", this);
}
};
class B {
public:
int b;
B()
{
printf("B::B()的this指针是:%p!\n", this);
}
void funcB()
{
printf("B::funcB()的this指针是:%p!\n", this);
}
};
class C : public A, public B
{
public:
int c;
C()
{
printf("C::C()的this指针是:%p!\n", this);
}
void funcC()
{
printf("C::funcC()的this指针是:%p!\n", this);
}
};
int main()
{
//this指针调整:多重继承
cout << sizeof(A) << endl;
cout << sizeof(B) << endl;
cout << sizeof(C) << endl;
C myc;
myc.funcA();
myc.funcB(); //已经被子类C覆盖了
myc.B::funcB();
myc.funcC();
return 1;
}
C类对象的内存结构图如下:
得出以下结论:
1.派生类对象 它是包含基类对象的.
2.如果派生类对象同时继承多个基类,那么大家就要注意:
2.1第一个基类子对象的开始地址和派生类对象的开始地址相同。
2.2后续这些基类子对象的开始地址 和派生类对象的开始地址相差 前边那些基类子对象所占用的大小,派生类的地址再加上这些类的大小就是后续基类子对象的地址也就是this指针的值.
二.只有一个基类
修改代码如下:
#include <iostream>
using namespace std;
class A {
public:
int a;
A()
{
printf("A::A()的this指针是:%p!\n", this);
}
void funcA()
{
printf("A::funcA()的this指针是:%p!\n", this);
}
};
class B {
public:
int b;
B()
{
printf("B::B()的this指针是:%p!\n", this);
}
void funcB()
{
printf("B::funcB()的this指针是:%p!\n", this);
}
};
class C : public A
{
public:
int c;
C()
{
printf("C::C()的this指针是:%p!\n", this);
}
void funcC()
{
printf("C::funcC()的this指针是:%p!\n", this);
}
};
int main()
{
//this指针调整:多重继承
cout << sizeof(A) << endl;
cout << sizeof(B) << endl;
cout << sizeof(C) << endl;
C myc;
myc.funcA();
myc.funcC();
return 1;
}
运行截图:
得出结论:
1.如果派生类只从一个基类继承的话,那么这个派生类对象的地址和基类子对象的地址相同。
三.总结
1.你调用哪个子类的成员函数,这个this指针就会被编译器自动调整到对象内存布局中 对应该子类对象的起始地址那去;