Table of Contents
1 实现原理
1.1 原始方式
#include <iostream> using namespace std; struct Person { int mAge; void info(const Person *p) { cout << p->mAge << endl; } }; int main() { Person p1, p2, p3; p1.mAge = 10; p2.mAge = 20; p3.mAge = 30; p1.info(&p1); p2.info(&p2); p3.info(&p3); getchar(); return 0; }
1.2 编译器将调用方法的对象地址传入调用方法中,就是 this 常指针
#include <iostream> using namespace std; struct Person { int mAge; void info() { cout << this->mAge << endl; } }; int main() { Person p1, p2, p3; p1.mAge = 10; p2.mAge = 20; p3.mAge = 30; p1.info(); p2.info(); p3.info(); getchar(); return 0; }
1.3 成员函数中的变量根据作用域链查找变量
- 函数内部变量
- 对象成员
- 对象外层
struct Person { int mAge; void info() { cout << mAge << endl; } };
1.4 本质
类似 js 函数调用,谁莱调用就传递谁(this 就是指向谁)
- 编译器只是把调用对象的地址传入成员函数
- 对象调用传递的是对象地址,指针调用传递的是指针地址中的内容(指针指向的地址)
- 函数使用成员函数会直接使用偏移量而不会管调用对象是个什么东西
#include <iostream> using namespace std; int mAge = 100; struct Person { int mAge; int mId; void info() { cout << "age: " << mAge << " id: " << mId << endl; } }; int main() { Person obj; obj.mAge = 10; obj.mId = 1001; Person* p1 = (Person *)&obj; Person* p3 = (Person*)&obj.mAge; Person* p2 = (Person*)&obj.mId; obj.info(); p1->info(); p2->info(); p3->info(); getchar(); return 0; }
Created: 2019-12-13 周五 18:06