2021-08-17

this指针

问题:如果调用的是同一个函数,那么编译器是怎么知道把变量放在不同对象的成员变量里?

class student
{
private:
	char _name[20];
	char _gender[4];
	int _age;
public:
	void SetstudentInfo(char *name, char *gender, int age);
	void PrintstudentInfo();
};
void student::SetstudentInfo(char *name, char *gender, int age)
{
	strcpy(_name, name); // 将 name 放给谁的_name里,是 d1._name 还是 d2._name 还是d3._name
	strcpy(_gender, gender);
	_age = age;

}
void student::PrintstudentInfo()
{
	cout << _name << "   " << _gender << "" << _age << "   " << endl;
}
int main()
{
	student d1, d2, d3;
	d1.SetstudentInfo("John", "man", 17);
	d2.SetstudentInfo("Brown", "man", 27);
	d3.SetstudentInfo("Mike", "man", 37);
	system("pause");
	return 0;
}

为什么编译器能够识别不同对象调用其公有的类成员函数?原因是编译器默认,在类成员函数中调用了一个 this 指针。this 代表着正在使用这个类成员函数的对象。通过这个this指针可以区别不同对象。

	d1.SetstudentInfo("John", "man", 17);
00EC5C38  push	11h  
00EC5C3A  push	0ECCC7Ch  
00EC5C3F  push	0ECCC88h  
00EC5C44  lea 	ecx,[d1]  
00EC5C47  call	student::SetstudentInfo (0EC1230h)  

编译器在调用函数的时候先使用了语句 lea ecx,[d1] 将这个对象的地址线保存起来,然后才调用SetstudentInfo函数。

  void student::PrintstudentInfo()
//void student::PrintstudentInfo(student const *this)
{
	cout << this->_name << "   " << this->_gender << "" << this->_age << "   " << endl;
}

编译器在编译过程当中,将类成员函数进行修改,将this添加进入函数。这样就可以识别不同对象的不同参数。this 指针存放在 ecx 寄存器,this指针不为空,因为是自动调用。

转载于:https://www.pianshen.com/article/618174657/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值