一.this指針的實作
#include<iostream>
using namespace std ;
<span style="font-family: Arial, Helvetica, sans-serif;">class Date1</span>
{
public:
void InitDate(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
protected:
int _year;
int _month;
int _day;
};
int main()
{
Date1 d1, d2, d3;
d1.InitDate(2016, 10, 8);
d2.InitDate(2016, 10, 7);
d3.InitDate(2016, 10, 9)
cout << "hello..." <<endl;
system("pause");
return 0;
}
這個程式在我們剛接觸C++不久,大家都能寫出來,但是我們是否考慮一個這樣的問題,類是如何知道對象d1,d2,d3調用成員函數呢?
這也就是我們這篇部落格的内容了,類的非靜态成員函數都隐藏了一個this指針,這個指針指向所調用的對象。
void InitDate(int year, int month, int day); 函數被改成void InitDate( Date * const this, int year ,int month ,int day);
d1.InitDate(2016,10,8) 在底層的實作是 InitDate(&d1,2016,10,8),
通過這種機制,類能清楚的知道是那個對象調用了類的成員函數。
因為存在this指針,如果類成員變量year和參數重名,我們可以通過this->year = year來操控成員變量
類中的靜态成員函數是屬于類的,不是屬于具體的對象。這個函數中沒有隐藏this指針。這個函數可以通過類+域作用符+函數名調用,也可以通過對象去調用。
如果類中有個成員函數static int fun(int a, int b).
d1.fun(1,2) 在 底層實作是fun(1,2)。
二、this經典題目分析
#include<iostream>
using namespace std ;
class CTest
{
public:
void FunTest()
{
cout<<this->data<<endl; //程式崩潰。 //空指針去通路資料成員,程式肯定崩潰。
}
int data;
};
void FunTest()
{
CTest* pt = NULL; //成員函數被解釋成FunTest(CTest * this)
pt->FunTest(); //編譯通過 這條語句被解釋成FunTest(pt)
}
int main()
{
FunTest();
return 0;
}
三. 關于this指針的一個精典回答:
當你進入一個房子後,
你可以看見桌子、椅子、地闆等,
但是房子你是看不到全貌了。
對于一個類的執行個體來說,
你可以看到它的成員函數、成員變量,
但是執行個體本身呢?
this是一個指針,它時時刻刻指向你這個執行個體本身。