his 是 C++ 中的一個關鍵字,也是一個 const 指針,它指向當前對象,通過它可以訪問當前對象的所有成員。
所謂當前對象,是指正在使用的對象。例如對于stu.show();,stu 就是當前對象,this 就指向 stu。
下面是使用 this 的一個完整示例:
#include
usingnamespacestd;
classStudent{
public:
voidsetname(char*name);
voidsetage(intage);
voidsetscore(floatscore);
voidshow();
private:
char*name;
intage;
floatscore;
};
voidStudent::setname(char*name){
this->name=name;
}
voidStudent::setage(intage){
this->age=age;
}
voidStudent::setscore(floatscore){
this->score=score;
}
voidStudent::show(){
cout<name<<"的年齡是"<age<<",成績是"<score<
}
intmain(){
Student*pstu=newStudent;
pstu->setname("李華");
pstu->setage(16);
pstu->setscore(96.5);
pstu->show();
return0;
}
運行結果:
李華的年齡是16,成績是96.5
this 只能用在類的內部,通過 this 可以訪問類的所有成員,包括 private、protected、public 屬性的。
本例中成員函數的參數和成員變量重名,只能通過 this 區分。以成員函數setname(char *name)為例,它的形參是name,和成員變量name重名,如果寫作name = name;這樣的語句,就是給形參name賦值,而不是給成員變量name賦值。而寫作this -> name = name;后,=左邊的name就是成員變量,右邊的name就是形參,一目了然。
注意,this 是一個指針,要用->來訪問成員變量或成員函數。
this 雖然用在類的內部,但是只有在對象被創建以后才會給 this 賦值,并且這個賦值的過程是編譯器自動完成的,不需要用戶干預,用戶也不能顯式地給 this 賦值。本例中,this 的值和 pstu 的值是相同的。
我們不妨來證明一下,給 Student 類添加一個成員函數printThis(),專門用來輸出 this 的值,如下所示:
voidStudent::printThis(){
cout<
}
然后在 main() 函數中創建對象并調用 printThis():
Student*pstu1=newStudent;
pstu1->printThis();
cout<
Student*pstu2=newStudent;
pstu2->printThis();
cout<
運行結果:
0x7b17d8
0x7b17d8
0x7b17f0
0x7b17f0
可以發現,this 確實指向了當前對象,而且對于不同的對象,this 的值也不一樣。
幾點注意:
this 是 const 指針,它的值是不能被修改的,一切企圖修改該指針的操作,如賦值、遞增、遞減等都是不允許的。
this 只能在成員函數內部使用,用在其他地方沒有意義,也是非法的。
只有當對象被創建后?this 才有意義,因此不能在 static 成員函數中使用(后續會講到 static 成員)。
this 到底是什么
this 實際上是成員函數的一個形參,在調用成員函數時將對象的地址作為實參傳遞給 this。不過 this 這個形參是隱式的,它并不出現在代碼中,而是在編譯階段由編譯器默默地將它添加到參數列表中。
this 作為隱式形參,本質上是成員函數的局部變量,所以只能用在成員函數的內部,并且只有在通過對象調用成員函數時才給 this 賦值。