C++——this指针
生活随笔
收集整理的這篇文章主要介紹了
C++——this指针
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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?指針。
#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;cout << this->length << endl ;cout << this->breadth << endl ;cout << this->height << endl ;}double Volume(){return length * breadth * height;}int compare(Box box){return this->Volume() > box.Volume();}private:double length; // Length of a boxdouble breadth; // Breadth of a boxdouble height; // Height of a box };int main(void) {Box Box1(3.3, 1.2, 1.5); // Declare box1Box Box2(8.5, 6.0, 2.0); // Declare box2if(Box1.compare(Box2)){cout << "Box2 is smaller than Box1" <<endl;}else{cout << "Box2 is equal to or larger than Box1" <<endl;}return 0; }/* 輸出結(jié)果是 Constructor called. 3.3 1.2 1.5 Constructor called. 8.5 6 2 Box2 is equal to or larger than Box1 */指向類(lèi)的指針
一個(gè)指向 C++ 類(lèi)的指針與指向結(jié)構(gòu)的指針類(lèi)似,訪問(wèn)指向類(lèi)的指針的成員,需要使用成員訪問(wèn)運(yùn)算符?->,就像訪問(wèn)指向結(jié)構(gòu)的指針一樣。與所有的指針一樣,必須在使用指針之前,對(duì)指針進(jìn)行初始化。
#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;cout << this->length << endl ;cout << this->breadth << endl ;cout << this->height << endl ;}double Volume(){return length * breadth * height;}int compare(Box box){return this->Volume() > box.Volume();}private:double length; // Length of a boxdouble breadth; // Breadth of a boxdouble height; // Height of a box };int main(void) {Box Box1(3.3, 1.2, 1.5); // Declare box1Box Box2(8.5, 6.0, 2.0); // Declare box2Box *ptr ; // 創(chuàng)建一個(gè)指向類(lèi)的指針ptr = &Box1 ; // 保存Box1對(duì)象的地址cout << ptr->Volume() << endl; // 使用成員訪問(wèn)運(yùn)算符來(lái)訪問(wèn)成員ptr = &Box2 ;cout << ptr->Volume() << endl;return 0; }/* 輸出結(jié)果是 Constructor called. 3.3 1.2 1.5 Constructor called. 8.5 6 2 5.94 102 */部分資料來(lái)源于菜鳥(niǎo)教程
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專(zhuān)家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的C++——this指针的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: C++——拷贝构造函数
- 下一篇: C++——static