日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++中關于this指針的入門介紹_C 語言

作者:幻荼 ? 更新時間: 2022-08-31 編程語言

簡介

C++編譯器給每個“非靜態的成員函數“增加了一個隱藏的指針參

數,讓該指針指向當前對象(函數運行時調用該函數的對象),在函數體中所有成員變量的操作,都是通過該指針去訪問。只不過所有的操作對用戶是透明的,即用戶不需要來傳遞,編譯器自動完成

特性

1. this指針的類型:類類型* const

2. 只能在“成員函數”的內部使用

3. this指針本質上其實是一個成員函數的形參,是對象調用成員函數時,將對象地址作為實參傳遞給this

形參。所以對象中不存儲this指針。

4. this指針是成員函數第一個隱含的指針形參,一般情況由編譯器通過ecx寄存器自動傳遞,不需要用戶傳遞

舉例

class Data {
public:
	void Printf()
	{
		cout << _year <<" "<<" "<< _month <<" "<< _day << endl;
	}
	void Init(int year=2022,int month=5,int day=25)
	{
		_year = year;
		_month = month;
		_day = day;
	}
private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	Data d1,d2;
	d1.Init(2022,1,1);
	d1.Printf();
	d2.Init(2022,2,2);
	d2.Printf();
	return 0;
}

這是一個簡單的日期類,那么這里有一個問題,我們在使用打印函數Printf和初始化函數Init的時候,d1和d2調用的是同一個函數,那么編譯器是怎么知道我是應該設置/打印d1還是d2呢?

這其實就使用了this指針

那么具體編譯器是怎么做的呢?

void Printf(const* this)//編譯器實際上處理的
	{
		cout << this->_year << " " << this->_month << " " << this->_day << endl;
	}
	void Printf()//我們看到的
	{
		cout << _year <<" "<<" "<< _month <<" "<< _day << endl;
	}
void Init(const* this,int year=2022,int month=5,int day=25)//編譯器處理的
	{
		this->_year = year;
		this->_month = month;
		this->_day = day;
	}
	void Init(int year = 2022, int month = 5, int day = 25)//我們看到的
	{
		_year = year;
		_month = month;
		_day = day;
	}
d1.Init(2022,1,1);//我們看到的
	d1.Init(&d1,2022, 1, 1);//編譯器實際上處理的

實際上編輯器取了d1和d2函數的地址,然后傳遞給了const*this,這樣編譯器就能自動打印和初始化相應的結構了。

注意

我們不能自己在傳參處加const*this和&,這是編譯器自己做的,我們不能搶了編譯器的活,即使做了,編譯也不會通過,但是里面我們可以加

void Printf(const* this)//錯誤
	{
		cout << _year <<" "<<" "<< _month <<" "<< _day << endl;
	}
void Printf()//可以運行,但是編譯器默認都會加this->,所以我們可以不用加,加了也沒事
	{
		cout <<this-> _year <<" "<<" "<< this->_month <<" "<< this->_day << endl;
	}

原文鏈接:https://blog.csdn.net/qq_62718027/article/details/124964421

欄目分類
最近更新