C++_this指针

8 篇文章 0 订阅
6 篇文章 0 订阅

一、this指针的引入

C++编译器给每个“非静态的成员函数”增加了一个隐藏的指针参数,让该指针指向当前对象(函数运行时调用该函数的对象),在函数体中所有成员变量的操作,都是通过该指针去访问。只不过所有的操作对用户是透明的,即用户不需要传递,编译器自动完成。

先来定义一个日期类

#include<iostream>
using namespace std;

class Date
{
public:
	void SetDateInfo(int year,int month,int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	void Print()
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};


int main()
{
	Date d1;
	Date d2;
	d1.SetDateInfo(2021, 7, 26);
	d2.SetDateInfo(2021, 8, 26);
	d1.Print();
	d2.Print();
	return 0;
}

以上代码定义了两个日期类d1,d2,编译器如何知道设置的数据是d1,还是d2的?
其实存在着这个指针–>this指针(隐藏起来了)
针对上述代码:this等价于Date* const
如d1.SetDateInfo(2021,7,26)就等价于Date::SetDateInfo(&d1,2021,7,26)
又如
在这里插入图片描述

二、this指针的特性

1.this指针的类型:类类型* const
2.只能在“成员函数”的内部使用
3.this指针本质上其实是一个成员函数的形参,是对象调用成员函数时,将对象地址作为实参传递给this形参,所以对象中不存储this指针。
在这里插入图片描述
4.this指针时成员函数第一个隐藏的指针形参,一般情况由编译器ecx寄存器自动传递,不需要用户传递。
在这里插入图片描述

面试题

1.this指针存在哪里

#include<iostream>
using namespace std;

class Date
{
public:
	void SetDateInfo(int year,int month,int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	void Print()
	{
		Date* const& rthis = this;
		cout << &rthis << endl;
		cout << this << endl;
		//cout << _year << "-" << _month << "-" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};


int main()
{
	Date d1;
	d1.Print();
	return 0;
}

在这里插入图片描述
画图如下

在这里插入图片描述
所以this指针在栈上

2.this指针可以为空吗

class A
{
public:
	void PrintA()
	{
		cout << _a << endl;
	}

	void Show()
	{
		cout << "Show()" << endl;
	}
private:
	int _a;
};

int main()
{
	A* p = nullptr;
	p->PrintA();
	p->Show();
}

看看编译的过程吧
在这里插入图片描述

编译可以通过,但是在访问变量的时候会崩溃
因为之前说到cout<<_a<<endl==cout<< this->_a<<endl,所以在访问时会崩溃
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值