0
点赞
收藏
分享

微信扫一扫

浅析C++的隐藏形参 this指针

科牛 2022-01-30 阅读 72
c++

首先我们先看下面的一段代码:

class Date  //日期类
{
public:
	void Init(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,d2;
	d1.Init(2022,1,12);
	d1.Print();
	
	d2.Init(2022,1,17);
	d2.Print();
	
	return 0;
}

首先我们要明确的一点是:在对象创建时,成员变量是保存在对象中的,而成员函数是存放在公共代码区。

其实类中的成员函数都有一个隐藏的指针形参,即 this指针
当对象调用成员函数时,会隐性地将对象地址作为实参传递给 this形参。也就是说,参数this指针会指向 调用该函数的对象。
因此,在函数体中有关成员变量的操作,都是通过该指针去访问的。

this指针是成员函数中的第一个隐含的指针形参,一般情况由编译器通过寄存器自动传递。这些操作对用户是透明的,不需要用户显式传递。

没错,实际相当于下面的代码注释:

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


int main()
{
	Date d1,d2;
	d1.Init(2022,1,12);  // d1.Init(&d1,2022,1,12);
	d1.Print();  // d1.Print(&d1);
	
	d2.Init(2022,1,17);  // d2.Init(&d2,2022,1,17);
	d2.Print();  // d2.Print(&d2);
	
	return 0;
}

this指针的特点
1.this指针的类型是:类型* const this。(比如:class Date,其成员函数中的this形参是 Date* const this)
2.调用成员函数时,不能显式传实参给this。(比如在上面的代码中,调用函数时不会写上实参 &d1和 &d2)
3.定义成员函数时,也不能显式声明形参this。(也就是代码中写 void Print() 就行)
4.在成员函数内部,我们可以显式使用this。(比如:在函数体内,可以写成 this->_year = year)
(第4点在有些场景下会用到,但一般情况下我们不显式使用this)

问:this存在哪儿?
答:因为 this指针本质上是成员函数的形参,所以其不存储在对象中。this指针一般情况下存在栈里,有些编译器会把它放到寄存器中。

举报

相关推荐

0 条评论