C++ this 指針
在 C++ 中,每一個(gè)對(duì)象都能通過(guò) this 指針來(lái)訪問(wèn)自己的地址。this 指針是所有成員函數(shù)的隱含參數(shù)。因此,在成員函數(shù)內(nèi)部,它可以用來(lái)指向調(diào)用對(duì)象。
友元函數(shù)沒(méi)有 this 指針,因?yàn)橛言皇穷?lèi)的成員。只有成員函數(shù)才有 this 指針。
下面的實(shí)例有助于更好地理解 this 指針的概念:
#include <iostream> using namespace std; class Box { public: // 構(gòu)造函數(shù)定義 Box(double l=2.0, double b=2.0, double h=2.0) { cout <<"Constructor 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; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; int main(void) { Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 if(Box1.compare(Box2)) { cout << "Box2 is smaller than Box1" <<endl; } else { cout << "Box2 is equal to or larger than Box1" <<endl; } return 0; }
當(dāng)上面的代碼被編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生下列結(jié)果:
Constructor called. Constructor called. Box2 is equal to or larger than Box1
更多建議: