C++——this指针
生活随笔
收集整理的這篇文章主要介紹了
C++——this指针
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
this指針
在 C++ 中,每一個對象都能通過?this?指針來訪問自己的地址。this?指針是所有成員函數的隱含參數。因此,在成員函數內部,它可以用來指向調用對象。
友元函數沒有?this?指針,因為友元不是類的成員。只有成員函數才有?this?指針。
#include <iostream>using namespace std;class Box {public:// 構造函數定義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; }/* 輸出結果是 Constructor called. 3.3 1.2 1.5 Constructor called. 8.5 6 2 Box2 is equal to or larger than Box1 */指向類的指針
一個指向 C++ 類的指針與指向結構的指針類似,訪問指向類的指針的成員,需要使用成員訪問運算符?->,就像訪問指向結構的指針一樣。與所有的指針一樣,必須在使用指針之前,對指針進行初始化。
#include <iostream>using namespace std;class Box {public:// 構造函數定義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 ; // 創建一個指向類的指針ptr = &Box1 ; // 保存Box1對象的地址cout << ptr->Volume() << endl; // 使用成員訪問運算符來訪問成員ptr = &Box2 ;cout << ptr->Volume() << endl;return 0; }/* 輸出結果是 Constructor called. 3.3 1.2 1.5 Constructor called. 8.5 6 2 5.94 102 */部分資料來源于菜鳥教程
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的C++——this指针的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++——拷贝构造函数
- 下一篇: C++——static