编译器对对象的加载步骤:
(1)类名
(2)成员变量
(3)成员方法
即使定义类时,成员变量写在成员方法后面,加载对象时,也是先加载成员变量
当编译器识别方法时,会对成员方法改写,在所有方法里隐藏一个this指针,用来保存当前对象的地址
在C语言中,
#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用法:
#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; }
当对象调用
void Goods::RegisterGoods(const char name[], int amount, float price)
这个函数时,就将这个函数改写成
void Goods::RegisterGoods(Goods *this, const char name[], int amount, float price)
this就保存当前对象
再来看看谁调用这个方法:
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); 执行这个函数时相当于编译器把这个调用改写成:
RegisterGoods(&c1, "C++",10, 12)
c2.RegisterGoods("Java", 5, 20);被改写成:
c2.RegisterGoods(&c2, "Java", 5, 20);
即把c1,c2对象的地址传给了this,this就保存了当前对象的地址
那么,内存中,同一个类的不同对象的内存怎么划分呢?
如上图,c1,c2,c3各自的成员变量值都不一样,所有都有自己的内存空间,而成员方法由于都是一样的,如果各自都有自己的内存空间,那就太浪费了
,那么三个对象的成员方法公用一个内存空间的话,如何区分成员函数是属于哪个对象呢?c++中,this就是用来区分不同对象的,当调用类的方法时,默认
把当前对象地址传递给this指针!跟C语言中结构体初始化有异曲同工之妙
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, "男"); }
原文:https://www.cnblogs.com/jacklovezzz/p/14674443.html