table of Contents
this pointer adjustment
explore
#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); } void funcB() { printf("C::funcB()的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; }
- Output result
Schematic diagram
to sum up
- Derived class objects contain sub-objects of the base class .
- If the derived class only inherits from one base class , then the address of the derived class object is the same as the address of the base class sub-object .
- But if the derived class object inherits multiple base classes at the same time, then we must pay attention to :
- The start address of the first base class object is the same as the start address of the derived class object .
- What is the difference between the start address of these subsequent base class sub-objects and the start address of derived class objects?
- Then you have to get rid of the memory space occupied by the previous base class sub-objects .
- Summary: You member function calls which subclass , the this pointer will be automatically adjusted to the compiler target memory layout of the start address should subclass object to that ;
(C++ Object Model): Adjust this pointer
Guess you like
Origin blog.csdn.net/baidu_41388533/article/details/108646950
Recommended
Ranking