C++进阶学习----this指针

this指针

this 是 C++ 中的一个关键字,也是一个 const 指针,不可以更改指向。指向当前对象,通过它可以访问当前对象的所有成员。

  • 成员函数最终会被编译成与对象无关的普通函数。除了成员变量,丢失所有信息
  • 相同类型的不同对象共享同一份成员函数代码。因此,编译时在成员函数中添加一个隐藏参数,将当前调用对象首地址传入,用来关联成员函数和成员变量,这就是this指针
  • C++关键字,const指针,在类的成员函数,构造函数和析构函数中,对所有成员的访问,都是通过this指针
#include<iostream>
#include<string>
using namespace std;
class GirlFriend
{
	int m_age;
	string m_name;
public:
	GirlFriend(int age,string name)
	{
		m_age = age;	//等价 this->m_age =age;
		m_name = name;	//等价 this->m_name =name;
		introduce();	//等价 this->introduce();
		cout << this << endl;	//打印this的地址
	}
	void introduce()
	{
		cout << "My name is:" << m_name << ",My age is:" << m_age << endl;
	}
	//introduce函数在编译器看来是这个样子
	//void introduce(GirlFriend* const this)
	//{
	//	cout << "My name is:" << this->m_name << ",My age is:" << this->m_age << endl;
	//}
};
int main()
{
	GirlFriend girl(18,"女朋友");
	cout << &girl<< endl;	//打印girl对象的地址
	cin.get();
	return 0;
}
//打印结果
My name is:女朋友,My age is:18
00CFF8F4
00CFF8F4

在上述代码运行结果中可以看出this指针指向的就是对象的地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DeRoy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值