c++类——this指针

如有兴趣了解更多请关注我的个人博客https://07xiaohei.com/

(一)引言:

在c++中,我们在类中创建成员函数,在创建类的对象后,在类的对象上使用类的成员函数可以访问类的此对象的数据。

那么这个成员函数是怎么知道要访问的是此对象的数据成员,而不是其他对象的呢?

其原因就是每个对象拥有的this指针——每个对象使用成员函数时通过传入自己的this指针来使成员函数能够确定要访问的对象。

下面对this指针进行详细介绍。

(二)概念:

定义:关键字this是指向对象自己的一个常量指针,,所以,this指针是不能够被赋值或者改变的。

this指针是成员函数的隐含形参,换言之,类的对象在正常为成员函数传入参数时,实际上最后还有一个额外的参数位置,参数类型是该类的常量指针,并含有默认值,默认值即为此调用对象的地址,在调用成员函数时,this指针作为实参被传入成员函数。

this指针本质上是成员函数的局部变量。

例子如下:

#include <iostream>
using namespace std;
class Simple
{
private:
	int x;
	int y;
public:
	Simple() = default;
	Simple (int a, int b) : x(a), y(b)
	{
		cout << "Finish the constructed function" << endl;
	}
	void resetXY(int a, int b) 
	{
		x = a,y = b;
		return ;
	}
	~Simple()
	{
		cout << "Finish deconstructor" << endl;
	}
};
int main()
{
	Simple s(1, 2);
	s.resetXY(2, 3); //在此处调用时,实际上是调用
					 //resetXY(2,3,Simple *const this)
					 //{ this->x=a,this->y=b;}
					 //使用了this指针
    return 0;
}

(三)this指针的注意要点:

  1. 作为常量指针,不能给this指针赋值

  2. this指针的作用域在类成员函数的内部,只能在成员函数内部,在类外无法获取。

  3. this指针的创建:

    this指针在成员函数的开始执行前构造,并在成员函数的执行结束后清除。

  4. 只有非静态成员函数才拥有this指针

    ​ ——友元函数不是类的成员函数,没有this指针。

    ​ ——静态函数不属于某个对象(详见c++类——静态成员)博客),没有this指针。

  5. this指针不可以显式声明,但可以显式使用。

    ​ ——显式使用是指可以在成员函数内调用this指针,比如使用this地址,(*this).x,this->x

    ​ x为数据成员/某些成员函数。

  6. this指针不是对象的一部分,其所占的内存大小不会反应在sizeof操作符上。

(四)this指针的显式使用样例:

#include <iostream>
using namespace std;
class Simple
{
private:
	int x;
	int y;
public:
	Simple() = default;
	Simple (int a, int b) : x(a), y(b)
	{
		cout << "Finish the constructed function" << endl;
	}
	void resetXY(int a, int b) 
	{
		x = a, y = b;
		return ;
	}
	void Simple_thisuse(int a,int b)
	{
		cout << this->x << " " << this->y << endl;
		(*this).x += a;
		(*this).y += b;
		cout << this->x << " " << this->y << endl;
		cout << this << endl;
		return;
	}
	~Simple()
	{
		cout << "Finish deconstructor" << endl;
	}
};
int main()
{
	Simple s(1, 2);
	s.resetXY(2, 3);
	s.Simple_thisuse(1, 1);
	return 0;
}

结果为:pp8l0u8.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

xiaohei07

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

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

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

打赏作者

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

抵扣说明:

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

余额充值