直接进入例子讲解
#include<iostream> using namespace std; class A { public: int a; A() { cout <<"A::A()的this指针是:" << this << endl; } void funca() { cout << "A::funca()的this指针是:" << this << endl; } }; class B { public: int b; B() { cout << "B::B()的this指针是:" << this << endl; } void funcb() { cout << "B::funcb()的this指针是:" << this << endl; } }; class C : public A, public B { public: int c; C() { cout << "C::C()的this指针是:" << this << endl; } void funcc() { cout << "C::funcc()的this指针是:" << this << endl; } }; int main() { cout << sizeof(A) << endl; cout << sizeof(B) << endl; cout << sizeof(C) << endl; C myc; myc.funca(); myc.funcb(); myc.funcc(); return 0; }
派生类对象 它是包含基类子对象的。
如果派生类只从一个基类继承的话,那么这个派生类对象的地址和基类子对象的地址相同。
但如果派生类对象同时继承多个基类,那么大家就要注意。
第一个基类子对象的开始地址和派生类对象的开始地址相同。
后续这些基类子对象的开始地址和派生类对象的开始地址相差多少呢?那就得把前边那些基类子对象所占用的内存空间干掉。
示意图:
#include<iostream> using namespace std; class A { public: int a; A() { cout <<"A::A()的this指针是:" << this << endl; } void funca() { cout << "A::funca()的this指针是:" << this << endl; } }; class B { public: int b; B() { cout << "B::B()的this指针是:" << this << endl; } void funcb() { cout << "B::funcb()的this指针是:" << this << endl; } }; class C : public A, public B { public: int c; C() { cout << "C::C()的this指针是:" << this << endl; } void funcc() { cout << "C::funcc()的this指针是:" << this << endl; } void funcb() { cout << "C::funcb()的this指针是:" << this << endl; } }; int main() { cout << sizeof(A) << endl; cout << sizeof(B) << endl; cout << sizeof(C) << endl; C myc; myc.funca(); myc.funcb(); myc.B::funcb(); myc.funcc(); return 0; }
总结:你调用哪个子类的成员函数,这个this指针就会被编译器自动调整到对象内存布局中对应的子类对象的起始地址那去。