this关键字理解
编译器对对象的加载步骤:
(1)类名
(2)成员变量
(3)成员方法
即使定义类时,成员变量写在成员方法后面,加载对象时,也是先加载成员变量
当编译器识别方法时,会对成员方法改写,在所有方法里隐藏一个this指针,用来保存当前对象的地址
在C语言中,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include "Test.h" using namespace std; struct Student { char name[10]; int age; char sex[3]; }; void InitStu(Student *_this, const char n[10], int a, const char s[3]) { strcpy (_this->name, n); _this->age = a; strcpy (_this->sex, s); } void main() { Student st; InitStu(&st, "风清扬" , 10, "男" ); } |
再来看C++中this用法:
1 2 3 4 5 6 7 8 9 | #include "Test.h" //void Goods::RegisterGoods(Goods *this, const char name[], int amount, float price) void Goods::RegisterGoods( const char name[], int amount, float price) { strcpy (Name, name); Amount = amount; Price = price; } |
当对象调用
1 | void Goods::RegisterGoods( const char name[], int amount, float price) |
这个函数时,就将这个函数改写成
1 | void Goods::RegisterGoods(Goods * this , const char name[], int amount, float price) this 就保存当前对象再来看看谁调用这个方法: |
1 2 3 4 5 6 7 8 9 10 | void main() { Goods c1, c2; //RegisterGoods(&c1, "C++",10, 12) c1.RegisterGoods( "C++" ,10, 12); //RegisterGoods(&c2, "C++",10, 12) c2.RegisterGoods( "Java" , 5, 20); } |
c1.RegisterGoods("C++",10, 12); 执行这个函数时相当于编译器把这个调用改写成:
1 | RegisterGoods(&c1, "C++" ,10, 12) |
1 | c2.RegisterGoods( "Java" , 5, 20);被改写成: |
1 | c2.RegisterGoods(&c2, "Java" , 5, 20);即把c1,c2对象的地址传给了 this , this 就保存了当前对象的地址那么,内存中,同一个类的不同对象的内存怎么划分呢? |
如上图,c1,c2,c3各自的成员变量值都不一样,所有都有自己的内存空间,而成员方法由于都是一样的,如果各自都有自己的内存空间,那就太浪费了
,那么三个对象的成员方法公用一个内存空间的话,如何区分成员函数是属于哪个对象呢?c++中,this就是用来区分不同对象的,当调用类的方法时,默认
把当前对象地址传递给this指针!跟C语言中结构体初始化有异曲同工之妙
1 2 3 4 5 6 7 8 9 10 11 12 | void InitStu(Student *_this, const char n[10], int a, const char s[3]) { strcpy (_this->name, n); _this->age = a; strcpy (_this->sex, s); } void main() { Student st; InitStu(&st, "风清扬" , 10, "男" ); } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· 因为Apifox不支持离线,我果断选择了Apipost!