在C++中,每一個對象都能夠通過this指針來訪問自己的地址。this指針是所有成員函數的隱含參數。因此,在成員函數內部,它可以用來指向調用對象。
友元函數是沒有this指針的,因為友元不是類的成員,只有成員函數才有this指針。
/*** this.cpp ***/ #include<iostream> using namespace std;class Box {public:Box(double l = 2.0,double b = 2.0,double h = 2.0){cout << "Construct called." << endl;length = l;breadth = b;height = h;}double Volume(){return length*breadth*height;}int compare(Box box){return this->Volume() > box.Volume();}private:double length;double breadth;double height; };int main() {Box box1(3.3,1.2,1.5);Box box2(8.5,6.0,2.0);if(box1.compare(box2)){cout<< "box2 is smaller than box1" << endl;}else{cout << "box2 is equal to or larger than box1" << endl; }return 0; }
運行結果:
exbot@ubuntu:~/wangqinghe/C++/20190807$ ./this
Construct called.
Construct called.
box2 is equal to or larger than box1
?
引用this:
當我們調用成員函數時,實際上時替某個對象調用它。
成員函數通過一個名叫this的額外隱式參數來訪問調用它的那個對象。當我們調用一個成員函數時,用請求該函數的對象地址初始化this。例如,如果調用的total.isbn()則服務器負責把total的地址傳遞給isbn的隱式形參this,可以等價地認為編譯器將該調用重寫了以下形式:
//偽代碼,用于說明調用成員函數的實際執行過程
Sales_data::isbn(&total)
其中,調用Sales_data的isbn成員時傳入了total的地址。
在成員函數內部,我們可以直接使用調用該函數的對象的成員,而無須通過成員訪問運算符來做到這一點,因為this所指的正是這個對象。任何對類成員的直接訪問都被看作時對this的隱式引用,也就是說,當isbn使用bookNo時,它隱式地使用this指向地成員,就像我們書寫了this->boolNo一樣。
對于我們來說,this形參是隱式的,實際上,任何自定義名為this的參數或變量的行為都是非法的。我們可以在成員函數體內部使用this,因為,盡管沒有必要,我們還是能把isbn定義為如下形式
std::string isbn() const {return this -> bookNo; }
因為this的目的總是指向“這個”對象,所以this是一個常量指針,我們不允許改變this中保存的地址
/***
this1.cpp
***/
#include<iostream>
using namespace std;
?
class Box
{
??? public:
??????? Box(){;}
??????? ~Box(){;}
??????? Box* get_address()
??????? {
??????????? return this;
??????? }
};
?
int main()
{
??? Box box1;
??? Box box2;
?
??? Box* p = box1.get_address();
??? cout << p << endl;
?
??? p = box2.get_address();
??? cout << p << endl;
?
??? return 0;
}
exbot@ubuntu:~/wangqinghe/C++/20190807$ g++ this1.cpp -o this1
exbot@ubuntu:~/wangqinghe/C++/20190807$ ./this1
0x7fffb05ed946
0x7fffb05ed947
?
this指針的類型可以理解為Box*
此時得到的兩個地址分別為box1和box2對象的地址。